Today I stumbled upon the following article. I encourage you to read the article, but for brevity I will sum it up. Basically, when creating a for loop in most C-based languages, there are two basic incrementation operators: Pre-increment (++i) and Post-increment (i++), with Post-increment being by far more common. From a functional standpoint, in C# they are equivalent within a loop and always produce the same output. The premise of the article is that while Post-incrementing is recommended by most computer science professors, due to it’s implementation in the ECMA standards it is actually slower than Pre-incrementation.
I tend to be a skeptic, so when I read the article I thought the author must have been mistaken. After all, I assumed that computer science is a field where something as common as the for loop would be well documented and understood by the academics. In order to test the author’s claim I decided to write some code to test how long it took each operator to iterate 1 billion times incrementing a variable on each iteration. Here is the code:
using System; namespace PostIncrementTest { class Program { static void Main(string[] args) { const long reps = 1000000000; for (int k = 0; k < 10; k++) { long temp = 0; // Define start time DateTime firstLoopStart = DateTime.Now; // Do a Post-Increment Loop for (long i = 0; i < reps; i++) { temp++; } // Define end time DateTime firstLoopEnd = DateTime.Now; temp = 0; // Define start time DateTime secondLoopStart = DateTime.Now; // Do a Pre-Increment Loop for (long i = 0; i < reps; ++i) { ++temp; } // Define end time DateTime secondLoopEnd = DateTime.Now; TimeSpan firstLoopTime = firstLoopEnd - firstLoopStart; TimeSpan secondLoopTime = secondLoopEnd - secondLoopStart; Console.WriteLine("The post-increment loop took {0} seconds", firstLoopTime.TotalSeconds); Console.WriteLine("The pre-increment loop took {0} seconds", secondLoopTime.TotalSeconds); } // Show that the operators produce the same output for(int i = 0; i < 10; i++) { Console.Write(i + " "); } Console.WriteLine(); for (int i = 0; i < 10; i++) { Console.Write(i + " "); } Console.ReadLine(); } } }
And the results:
While there is a measurable difference between the two operators, it is so minute that over the course of 1 billion iterations it only amounted to .02 seconds difference on average on my machine. In a loop used in an every day program, this would most likely make no measurable difference. Although the difference was minute, I may still start using the Pre-increment operator since it is such a small change.