Wednesday, March 2, 2016

C# Speed Test - Basic Loops Anomaly

For the longest time, I have been curious about the efficiency of different algorithms. So I built this page to learn some of the basic time duration of simple code like an empty loop, multiple increments, and datetime assignment.

The page developed: http://dlastlee.com/Apps/Tools/CSMetricsIncrementSpeedTest.aspx

Anomaly

While testing, I found an anomaly with one of the speed tests. Looping a variable that increments runs faster than a loop that does nothing (i.e. noop or nop or no operation).

for (int i=0;i<1000000;i++) j++;
vs

for (int i=0;i<1000000;i++) { }

And this is always the case no matter how many times I run the test. I do not have an answer for this except maybe increments is more efficient running through pipelines than NOPs.


Other Findings

Azure server is about 6-7x faster than my laptop where the empty loop ran about 0.015 seconds on Azure vs 0.07 seconds on my laptop. 

DateTime is 20x slower than a simple increment or null.

Declaring a new DateTime is barely slower than declaring a DateTime variable outside the loop. This is more noticeable