.NET乘法优化乘法、NET

2023-09-04 09:38:26 作者:真是个可爱鬼

该编译器优化任何乘法1?也就是考虑:

  INT A = 1;
INT B = 5 *一个;
 

请问EX pression 5 *一个被优化成只有5?如果不是,将它,如果一个被定义为:

  const int的一个= 1;
 

解决方案

这将pre-计算任何常量EX pressions时汇编,其中包括字符串连接。如果没有在 常量 将被单独留在家中。

.NET性能优化方法总结 pdf版

您第一个例子编译这个IL:

  .maxstack 2
.locals的init([0] INT32,[1] INT32)

ldc.i4.1 //负载1
stloc.0 //店1日局部变量
ldc.i4.5 //负荷5
ldloc.0 //装载第一个变量
MUL // 1 * 5
stloc.1 //存储在第二局部变量
 

第二个例子编译到这一点:

  .maxstack 1
.locals的init([0] INT32)

ldc.i4.5 //负荷5
stloc.0 //存储到本地变量
 

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;

解决方案

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