views:

78

answers:

3

Hi,

Suppose we want to loop through all the items in a dropdown list and no item is added or removed while we are looping. The code for it is as follows:

for (int i = 0; i < ddl.Items.Count; i++)
{
    if (ddl.Items[i].Text == text)
    {
        found = true;
        break;
    }
}

If it is changed to this:

for (int i = 0, c = ddl.Items.Count; i < c; i++)
{
    if (ddl.Items[i].Text == text)
    {
        found = true;
        break;
    }
}

Is there any performance gain? Does the compiler do something clever not to read the Count property every iteration?

A: 

I've read that the JIT compiler is smart enough to figure out you are looping through the entire array and would therefore skip emitting bounds checking code inside the body of the loop.

It might not be smart enough to figure that out in the second case.

I guess the best answer is to profile it and see for yourself.

Senthil Kumar
+2  A: 

I suggest another optimization. Cache the value of Items property. If Items property itself is performance intensive (as some WinForms properties are, contrary to how they look), it can be very inefficient to loop. For instance, see: why foreach is faster than for loop while reading richtextbox lines.

Also, if you don't need the index, why don't you use foreach. It's easier to read and less prone to errors.

Mehrdad Afshari
A: 

I suggest you, that, if you think that it plays a important role, you should be familiar with ILDasm which is used to generate IL code, and CorDbg tool which is normally used to generate JIT compiled code.

VP