罗斯林(Roslyn)没有优化多个增量的原因吗? [英] Is there a reason why Roslyn does not optimize multiple increments?
问题描述
我试图查看 Roslyn
如何优化以下代码段:
I was trying to see how Roslyn
optimizes the following snippet:
代码
public int F(int n) {
++n;
++n;
++n;
++n;
return n;
}
asm
C.F(Int32)
L0000: inc edx
L0002: inc edx
L0004: inc edx
L0006: inc edx
L0008: mov eax, edx
L000a: ret
问题
为什么Roslyn不能像MSVC这样的提前C编译器那样对其进行优化? 4 x INC
较慢(即使假设消除了移动,延迟为4个周期,而1个为4个周期,并且吞吐量需要多于4个oups; C
等效";其中:
int
f(void *dummy_this, int n) {
++n;
++n;
++n;
++n;
return n;
}
来自MSVC的
asm 或具有 __ attribute __((ms_abi))
的GCC,以使用与C#asm相同的Windows x64调用约定: https://godbolt.org/z/sK6h7KKcn
asm from MSVC, or GCC with __attribute__((ms_abi))
to use the same Windows x64 calling convention as the C# asm: https://godbolt.org/z/sK6h7KKcn
f:
lea eax, [rdx+4]
ret
推荐答案
编译器确实进行了优化.但是 n
是一个参数,因此无法修改.JIT编译器必须修改参数值的副本.
The compiler does optimize. n
is a parameter though, so it can't be modified. The JIT compiler must modify a copy of the parameter's value.
如果在递增之前将值分配给变量,则Roslyn编译器将消除增量.来自
If the value is assigned to a variable before incrementing, the Roslyn compiler will eliminate the increments. From this Sharplab.io snippet, this C# code :
public int F(int i) {
var n=i;
++n;
++n;
++n;
++n;
return n;
}
将被翻译为
public int F(int i)
{
return i + 1 + 1 + 1 + 1;
}
并最终编译为以下汇编代码:
And eventually compiled to this assembly code:
C.F(Int32)
L0000: lea eax, [edx+4]
L0003: ret
这篇关于罗斯林(Roslyn)没有优化多个增量的原因吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!