Performance: Don't rely on the C# compiler to optimize your math...
The C# compiler generally does a good job of optimizing your math, but it isn't always the case. I was going through some interesting code in the .NET Terrarium where we approximated the magnitude of a vector by using a Taylor series. What I found strange was that the true magnitude and the approximation were coming up to the same speed.
time(Math.Sqrt(x*x + y*y)) = time(absX + absY - absX / 2)
I always thought that numeric literals involved in division would be turned into multiplication instead. Multiplication is a hell of a lot faster than division. We can drastically increase the speed of the function by taking note of this.
time(absX + absY - absX * 0.5D) // This is about 3 times faster now
Note there is some extra work involved in the approximation where we pick absolute values, etc... And there is a branch instruction that controls whether or not we subtract half of absX or half of absY... We can go one step further to simplify the equation and get rid of one of the subtractions.
time(absX * 0.5D + absY), time(absX + absY * 0.5D)
The function will be selected depending on the branch instruction. The morale of the story is that at some point we had to do some testing and find out that the Taylor series function was faster at computing the magnitude of the vector. However, at some point later the JIT changed, or maybe something else changed and all of the performance of the function was lost. Of course we based the performance on an assumption of optimization instead of a real optimization. By simply changing the algorithm a bit we get all of the performance back.
The really sad thing is that the approximated magnitude caused some major issues for people playing the game. In fact we eventually created a series of properties so you could get the approximate magnitude but also the real magnitude. Too bad the engine continued to use the slow approximate method rather than upgrading to the more accurate measure.