## Micro-Optimization for C# Loops

I was recently trying some of the basic problems from Project Euler, which is highly recommendable for interesting problems to solve that also teach you lessons on how to improve the way you code.

I had to optimise the loop that I was doing a for through a large amount of items with each increment performing a computation. To shave 10ths of a second from my computation I tried micro-optimising by using a decrementing loop.

Here's a generalised version of what I did

Let max be the number that you want to loop until.

Incremental Loop

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


Decremental Loop

for (int i = max - 1;  i >= 0;  i--) {
}


Things to note

• The decremented version is only faster when the calculation of max-1 is less complex than whatever is in the curly braces.
• From a high level view, the reason that the decremental loop is faster is that most CPUs already have a decrement to zero functionality in-built so on an MSIL level it is just duplicating a section of this code. Whereas incrementing to an arbitrary maximum is not something that is fundamental.
• This only makes the performance notably faster if there are many items to iterate through, there are nested loops and also it the code within the curly braces is relatively time consuming.

Good discussions and articles on this

Anyone with better explanations of why decrementing is better, feel free to comment...