Why does my CPU-heavy A/I run so slow in Unity?

Polygame is a player for abstract games and puzzles. To play well the A/I does a tree search on available moves to find the best. For a sample game it needs to consider about 100,000 positions and that takes about 5.5 seconds outside Unity. In Unity that identical code takes 19.0 seconds to run. Why?

The code is identical: Polygame is built as a DLL library and imported into Unity. I’m testing the same binary.

The code is written to do incremental update using a Coroutine, and I can vary the parameters. It makes almost no difference whether the frame count is 1, 2, 5 or 20, the total elapsed time to do the tree search is the same. It isn’t frame overhead causing the problem.

So what is it? And more important, is there anything I can do to fix it? A slow-down of nearly x4 is pretty bad.

Try running the unity profiler to see where in the code the time is used up and if there is any garbage being generated. The fact that it is slower in unity might indicate that it has to do with the mono runtime (I assume that the 5.5 second test is done with standard .Net runtime?).

The mono runtime is slower in some cases, especially where there is garbage generated, but there may be other cases as well were it might be slower so running the profiler just might give you the hint you need. Maybe you wrote some code that the standard .Net runtime handles just fine but the mono runtime does slow. In that case it might be possible to fix. Or if you are unlucky the mono runtime is just slower or the overhead of the Unity engine is killing your performance.