Search code examples
c#.netoptimizationmultiplication

.NET multiplication optimization


Does the compiler optimize out any multiplications by 1? That is, consider:

int a = 1;
int b = 5 * a;

Will the expression 5 * a be optimized into just 5? If not, will it if a is defined as:

const int a = 1;

Solution

  • It will pre-calculate any constant expressions when it compiles, including string concatenation. Without the const it will be left alone.

    Your first example compiles to this IL:

    .maxstack 2
    .locals init ([0] int32, [1] int32)
    
    ldc.i4.1   //load 1
    stloc.0    //store in 1st local variable
    ldc.i4.5   //load 5
    ldloc.0    //load 1st variable
    mul        // 1 * 5
    stloc.1    // store in 2nd local variable 
    

    The second example compiles to this:

    .maxstack 1
    .locals init ( [0] int32 )
    
    ldc.i4.5 //load 5 
    stloc.0  //store in local variable