Question

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;
Was it helpful?

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

OTHER TIPS

Constant propagation is one of the most common and easiest optimisations.

Looking at the code generated by the mono compiler, the version with the non-const a performs the multiplication at run time. That is, the multiplication is not optimized out. If you make a const, then the multiplication is optimized out.

The Microsoft compiler might have a more aggressive compiler, the best solution is to look at the code generated by the compiler to see what it is doing.

What the compiler would optimise here is not multiplication by 1 per-se, but rather arithmetic with values known at compile-time. So yeah, a compiler would optimise out all the maths in your example, with or without the const.

Edit: A competent compiler, I should say.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top