Dot Net Perls

Decrement Loop Optimization - C#

by Sam Allen

Problem

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.

Solution: C# loop iterations

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.

Question: why test against zero?

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 zeroLoop 2: count up to max
for (int i = Max - 1; i >= 0; --i) { // do something }for (int i = 0; i < Max; i++) { // do something }

Information: benchmark results

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.

Summary: reversing your loops

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.

Dot Net Perls
About
Sitemap
Source code
RSS
Integers
Use int.Parse for Integer Conversion
Random Number Generator Use
Numeric Types and Casts
int Max and Min Constants
Math.Max and Min for Bounds-Checking
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.