.NET乘法优化

问题描述 投票:0回答:4

编译器是否会优化任何乘以 1 的运算?也就是说,考虑:

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

表达式 5 * a 会被优化为 5 吗?如果不是,如果 a 定义为:

const int a = 1;
c# .net optimization multiplication
4个回答
14
投票

它会在编译时预先计算任何常量表达式,包括字符串连接。如果没有

const
,它将被单独留下。

您的第一个示例编译为此 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 

第二个示例编译为:

.maxstack 1
.locals init ( [0] int32 )

ldc.i4.5 //load 5 
stloc.0  //store in local variable

1
投票

恒定传播是最常见和最简单的优化之一。


1
投票

查看 mono 编译器生成的代码,带有非常量 a 的版本在运行时执行乘法。 也就是说,乘法没有被优化。 如果你创建一个 const,那么乘法就会被优化。

微软编译器可能有更激进的编译器,最好的解决方案是查看编译器生成的代码,看看它在做什么。


0
投票

编译器在这里要优化的并不是乘以 1 本身,而是使用编译时已知的值进行算术运算。所以是的,无论有没有

const
,编译器都会优化示例中的所有数学。

编辑:我应该说,这是一个有能力的编译器。

© www.soinside.com 2019 - 2024. All rights reserved.