Dll call 10x slower in Unity

I’ve written a Monte-Carlo based AI for an abstract strategy game (Eg: a game like Chess) and compiled it into a dll. When I run this code from a console application it runs fine, but from Unity it takes 10x longer to get the same result.

There is not a lot of interop between Unity and the dll. Here is the basic architecture…

On start, Unity creates a thread for the game to run in. When the game is instantiated ‘controllers’ can be attached to the players to feed the game input. Likewise ‘viewers’ can be attached that notify of a new game state (to display the UI, for instance) This is how communication with Unity is done - only when the game asks for a move or notifies that a move has been made.

The MonteCarlo part is a ‘controller’. It fires up 8 threads and churns on a bunch of numbers for a while without leaving the dll. That’s about it… pretty simple.

How could it be that it is running so much slower in Unity?

Could it be memory allocations? Garbage Colection is different under Unity.

I am experiencing the very same 10x slowdown in calls to my native code in Unity as well (Even on pure computational calls, where nothing is allocated or something like that).
This happens both on Windows and Linux with Unity 2017.2 - 2018.2.

To work around this 10x slowdown, I have to reimport the *.cs Files in Unity after every launch.
This brings the performance back to where it should be in the first place.