I’m annoyed of how developers used to organize loops…



By ganton ~ November 4th, 2008. Filed under: Other.

Today, I browse the code of one of our projects in order to look through a problem I discussed with another developer and I saw a loop which irritated me. The sample of what I’m talking about is below.

object obj = null;
foreach (int item in array)
{
// initialize the object if the first pass
if (obj == null)
{
obj = new object();
}
// do some work
}

I really do not like when I found a loop where we have a check and after the check we initialize an object. I became even more irritated of the comment. But why to write such code? I didn’t found any reason for organizing the loop such a way. Why I do not like it? First of all because it is not well formed and if you have a more then 20 lines of code in the loop and another 5 in the if statement it becomes not exactly clear. The second and not the least thing is that it is slower with the if statement then without it.

I can offer several variants of how to do the same and it will work faster and the logic will be the same as it is in the cycle. The first variant is just to initialize the object before to go to the loop. The disadvantage of this variant is that if we initialize some heavy object it will take some time may be more then the time of all loop checks.


obj = new object();
foreach (int item in array)
{
// do some work
}

In the case we have a heavy object for initialization we can use the variant below.


if (array.Count > 0)
{
obj = new object();
foreach (int item in array)
{
// do some work
}
}

Of course we also can use a variant with IEnumerator. It is a very elegant snippet (see below) but it will get much more time then others because of the call of a function.


IEnumerator enumerator = array.GetEnumerator();
if (enumerator.MoveNext())
{
obj = new object();
DoWork();
}
while(enumerator.MoveNext())
{
DoWork();
}

I test the performance of all variants with an array of 10000000 entries and the results are below.

I know somebody can say come on man it is not so much time difference. Yes, I know that but in any case I do not like the initial variant because it is also not elegant and doesn’t look well. Of course, it is my opinion and everybody can write code in his/her way.

Leave a Reply