Search code examples
c#optimization

How does the C# compiler optimize a code fragment?


If I have a code like this

for(int i=0;i<10;i++)
{
    int iTemp;
    iTemp = i;
    //.........
}

Does the compiler instantinate iTemp 10 times?

Or it optimize it?

I mean if i rewrite the loop as

int iTemp;
for(int i=0;i<10;i++)
{
    iTemp = i;
    //.........
}

Will it be faster?


Solution

  • Using reflector you can view the IL generated by the C# compiler.

    .method private hidebysig static void Way1() cil managed
    {
        .maxstack 2
        .locals init (
            [0] int32 i)
        L_0000: ldc.i4.0 
        L_0001: stloc.0 
        L_0002: br.s L_0008
        L_0004: ldloc.0 
        L_0005: ldc.i4.1 
        L_0006: add 
        L_0007: stloc.0 
        L_0008: ldloc.0 
        L_0009: ldc.i4.s 10
        L_000b: blt.s L_0004
        L_000d: ret 
    }
    
    .method private hidebysig static void Way2() cil managed
    {
        .maxstack 2
        .locals init (
            [0] int32 i)
        L_0000: ldc.i4.0 
        L_0001: stloc.0 
        L_0002: br.s L_0008
        L_0004: ldloc.0 
        L_0005: ldc.i4.1 
        L_0006: add 
        L_0007: stloc.0 
        L_0008: ldloc.0 
        L_0009: ldc.i4.s 10
        L_000b: blt.s L_0004
        L_000d: ret 
    }
    

    They're exactly the same so it makes no performance difference where you declare iTemp.