Deserialized The Ramblings of a Web Architect

19Aug/091

Comparing while() loops with for() loops in C#

There is always a lot of debate about the speed and performance of loops in any language.  I was curious to see what the differences were between a for() loop and a while() loop in C# and ultimately the .NET CLR.

What I found was no big surprise to me, as it simply confirms what I have been reading for many years.  While loops are simply faster and less complex than for loops.  I did a very simple test to verify this.  I created two loops that contained empty bodies.  You can see them below:

public void doFor()
{
    int i = 0;
    int len = 100;

    for (i = 0; i < len; i++)
    {

    }
}
public void doWhile()
{
    int i = 100;
    while (i-- == 0)
    {

    }
}

As you can see, both of these loops are as basic as they can be and have no inner bodies to complicate the CIL.  Lets take a look at the generated CIL for each of them.

The generated CIL for a for() loop

.method public hidebysig instance void doFor() cil managed
{
    .maxstack 2
    .locals init (
        [0] int32 i,
        [1] int32 len)
    L_0000: ldc.i4.0
    L_0001: stloc.0
    L_0002: ldc.i4.s 100
    L_0004: stloc.1
    L_0005: ldc.i4.0
    L_0006: stloc.0
    L_0007: br.s L_000d
    L_0009: ldloc.0
    L_000a: ldc.i4.1
    L_000b: add
    L_000c: stloc.0
    L_000d: ldloc.0
    L_000e: ldloc.1
    L_000f: blt.s L_0009
    L_0011: ret
}

The generated CIL for a while() loop

.method public hidebysig instance void doWhile() cil managed
{
    .maxstack 3
    .locals init (
        [0] int32 i)
    L_0000: ldc.i4.s 100
    L_0002: stloc.0
    L_0003: ldloc.0
    L_0004: dup
    L_0005: ldc.i4.1
    L_0006: sub
    L_0007: stloc.0
    L_0008: brfalse.s L_0003
    L_000a: ret
}

The results are in and there is no surprise.

As you can see, the generated CIL for a for() loop is larger by 6 instructions. Furthermore, in this code the for() loop initializes 2 local variables rather than 1 (but this may vary depending on your code).

What does it all mean?

Probably nothing.  6 more instructions and an additional variable declaration will in most cases have no impact on the performance, even if you are measuring in microseconds.  I am curious to see what the resulting difference between the loops above would be in other languages.

Filed under: C# Leave a comment
Comments (1) Trackbacks (0)
  1. But these two loops are not same. In for loop you are using less than and in the other you are using equals and one of them is going forward and the other is going backward thus utilizing early initialization – which I don't think that initialization will create an effect but still effects the logic. Loops are not working in the same logic, so the comparison is not healthy.


Leave a comment

(required)

No trackbacks yet.