.NET multiplication optimization

為{幸葍}努か 提交于 2019-12-08 17:34:12

问题


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;

回答1:


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



回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/160848/net-multiplication-optimization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!