Unity game optimization means no LINQ

Last week I implemented the first version of the computer opponent for Vaults Inc. It is not very smart, but It might give players some challenge.
It uses a mix set of arbitrary rules (like “always try to buy the most expensive tile available”) and simulation (test each combination to get the most reputation possible).
Then I wanted to put 2 bot opponents to fight! I would be just an spectator. It worked fine. However… the performance is horrible! horrible horrible! Specially mid-to-final turns, the combinatorial analysis was exponentially slower.
It was making the game hang. The logical step is to make code optimization as a urgent task. Code branched and the analysis began.
The first thing I discovered was LINQ was performing VERY badly. So sad. I love using LINQ queries to create clean code; in one line it filters lists in very nice ways. But LINQ generates simple enumerators, which is perfect if you want later iterate all items, but very bad if you want some kind of management data, like the quantity of items found. If you ask it, it will iterate all items each time just for you. Surprisingly, the ANY() function, used to check if there is at least one item, was also super slow.
Removing essentially all LINQ from the game, It was still slow. The next thing I had to attack was the lack of cache on recurring operations.
The next target was the messaging system. To decouple each class from the other, I used a event system that was too generic. Each listener (hundreds of them) had to deal with all calls all the time. Just by rewriting some of the implementations resulted in a much better speed.
The last piece was the hex grid system. One of the most repetitive tasks was finding if a given tile is adjacent to another. The code was creating a list of possible tiles and them checking if the tile you want to check is among any of them. It was not good due the memory allocation it was generating each time. I had to remake the logic using just math.
There is room for many more improvements. I will just attack a few more points and them invest on new features again.

The post was originally on