Optimize loops in C# by testing your iterator variable against zero. You want to optimize the loops in any computer language. You want your loops to go faster by changing a single line of code.
You can change loops to test against zero, which can sometimes slightly enhance performance. This also works in C++ and many other languages. The approach is called testing against 0 and iterating down instead of up.
X86 chips, including Pentium, Celeron, Core 2 Duo, and AMD Athlon, have special instructions and optimizations for testing against zero. The following two loops show how you can rewrite your loops.
| Loop 1: count down to zero | Loop 2: count up to max |
| for (int i = Max - 1; i >= 0; --i) { // do something } | for (int i = 0; i < Max; i++) { // do something } |
The above code was benchmarked and the second version that tests against zero was found to be faster. Keep in mind that the difference here is minimal.
Decrementing a variable in a loop is twice as fast. On a modern 2 GHz computer, this will save you 1 millisecond per million iterations. That means testing against zero is a millionth of millisecond faster. This is of extremely minimal value in 99% of programs.
Please don't go out of your way to use this optimization. It is mostly here just for interest and to help gain insight into processor behavior and tricks.