这个 CIL 代码是做什么的?为什么需要第3步?
在我正在阅读的书中“_Pro C# 2008 and the .NET Platform”,有一章是关于 CIL 的,其中有一些我感到困惑的代码。
为什么突出显示的步骤是必要的?正如我所见,这就是代码正在做的事情。
- 创建一个局部整数变量“i”并初始化为 0(由于整数总是) 。如果没有显式赋值则初始化为 0)
- (IL_0000) 局部变量 [0](即“i”)的值被加载到堆栈中
- (IL_0001) 然后该值从堆栈中弹出并分配给“i” “再说一次……为什么?“i”已经是 0!
In the book I'm reading _Pro C# 2008 and the .NET Platform" there is a chapter on CIL with some code that I am confused about.
Why is the step highlighted necessary? As I see it, this is what the code is doing.
- A local integer variable "i" is created and is initialized to 0 (by virtue of integers are always initialized to 0 if not explicitly assigned a value)
- (IL_0000) The value of the local variable [0] (which is "i") is loaded onto the stack
- (IL_0001) Then the value is popped off the stack and assigned to "i" again . . . WHY? "i" is already 0!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从内存的角度来看,您可以认为没有必要将 i 初始化为 0,因为初始化的 int32 变量的默认值为 0。
但是,编译器会在源代码中保留循环的语义信息。毕竟,变量 i 在 for 语句中被赋值为 0,并且该信息最终在 IL 中序列化。无论如何,这个语句很可能会被 JIT 优化掉。至少 Mono 的 JIT 是这样做的。从 CIL 的角度来看,它可以很容易地看到发生了什么:
在 CIL 级别,for 基本上是:
很容易直观地识别上面 CIL 中元素的不同之处。
From a memory standpoint, you could consider the initialization of i to 0 unnecessary, as the default value of an initialized int32 variable is 0.
However, the compiler is preserving the semantic information of the loop in the source code. The variable i is, after all, assigned to 0 in the for statement, and this information ends up serialized in the IL. It's likely that this statement will be optimized away by the JIT anyway. At least Mono's JIT does so. From the CIL standpoint it makes it easy to see what's happening:
At the CIL level, a for is basically:
It's quite easy to visually identify the different for elements in the CIL above.