Okay, while trying to figure out why some of my pure math code was running sluggish, I decided to see how the low level math ran on the phone. Stuff like, should I use an int, float or double? How much faster is a bit shift than multiplication?
I wrote a quick Silverlight page that runs a test method (on the UI thread) and does a whole bunch of math in loops. I also used the Compiler Services namespace to hide the method from the debugger and turn off optimizations.
This is probably the least scientific test of performance, but it’ll do in a pinch. I’ve used integer addition on the emulator as the base (int add = 1) and calculated everything from there. So, it is in units of integer additions on the emulator running on my machine.
Note: there was a play of about +- 0.2 when running multiple times. It was even higher ( +- 0.5) for division.
Here are the results:
|int -> float||2.8||3.9|
|float <- int||2.5||1.9|
|int -> double||1.7||2.7|
|double -> int||3.3||1.9|
|float -> double||2.2||1.9|
|double -> float||3.3||2.4|
There you have it. In general, don’t divide (or modulus)! If you need to divide, use floats or doubles.
Integers barely outperform floats and doubles, it is close enough that I’d call them equal.
Casting isn’t nearly as bad as I thought it would be – with casting to an Integer being practically zero extra cost!
I wouldn’t plan your whole performance strategy around these numbers… try it on your own! Let me know what you get.