Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-loop optimization - needed or not?

Do I have to optimize my FOR-loops like below or the compiler will do that for me?

//this is slow, right?
for (int i = 0; i < menuItem.DropDownItems.Count; i++)
{
    ...
}

//this should be much faster right?
for (int i = 0, count = menuItem.DropDownItems.Count; i < count; i++)
{
    ...
}

PS. I bet this was already posted but I haven't found anything, sorry for a possible dup.

PPS. Sorry, I code a lot of JavaScript - where we have to think these kind of optimizations... May seem ridiculous in .net-world.

like image 735
Alex from Jitbit Avatar asked Dec 18 '10 08:12

Alex from Jitbit


People also ask

Why is loop optimization very important?

Loop optimization is most valuable machine-independent optimization because program's inner loop takes bulk to time of a programmer. If we decrease the number of instructions in an inner loop then the running time of a program may be improved even if we increase the amount of code outside that loop.

How does compiler optimize for loop?

Loop invariant computation The variables operation and x are loop invariant, i.e. they don't change the value while the loop is running. A smart compiler can then calculate the value of the expression x*x outside of the loop and reuse it everywhere in the loop. This optimization is called loop invariant code motion.

How can I improve my loop performance?

The best ways to improve loop performance are to decrease the amount of work done per iteration and decrease the number of loop iterations. Generally speaking, switch is always faster than if-else , but isn't always the best solution.


1 Answers

Well, it depends on how DropDownItems.Count is implemented - but frankly it's likely to be a simple field-backed property... which would make the first code just as fast as the second, but much more readable.

Readability first - then measure performance and micro-optimize only where necessary.

Where possible, prefer a foreach loop to start with though... again, on grounds of readability.

Even if you do want to use a temporary variable, I would keep the for loop itself simple, hoising the count out to separate variable. Admittedly it means a wider scope, but it's simpler:

int count = menuItem.DropDownItems.Count;
for (int i = 0; i < count; i++)
{
    ...
}

That much is just personal preference though.

like image 165
Jon Skeet Avatar answered Oct 05 '22 05:10

Jon Skeet