这个 CIL 代码是做什么的?为什么需要第3步?

发布于 2024-11-04 02:23:49 字数 362 浏览 2 评论 0原文

在我正在阅读的书中“_Pro C# 2008 and the .NET Platform”,有一章是关于 CIL 的,其中有一些我感到困惑的代码。

在此处输入图像描述

为什么突出显示的步骤是必要的?正如我所见,这就是代码正在做的事情。

  1. 创建一个局部整数变量“i”并初始化为 0(由于整数总是) 。如果没有显式赋值则初始化为 0)
  2. (IL_0000) 局部变量 [0](即“i”)的值被加载到堆栈中
  3. (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.

enter image description here

Why is the step highlighted necessary? As I see it, this is what the code is doing.

  1. 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)
  2. (IL_0000) The value of the local variable [0] (which is "i") is loaded onto the stack
  3. (IL_0001) Then the value is popped off the stack and assigned to "i" again . . . WHY? "i" is already 0!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遇到 2024-11-11 02:23:49

从内存的角度来看,您可以认为没有必要将 i 初始化为 0,因为初始化的 int32 变量的默认值为 0。

但是,编译器会在源代码中保留循环的语义信息。毕竟,变量 i 在 for 语句中被赋值为 0,并且该信息最终在 IL 中序列化。无论如何,这个语句很可能会被 JIT 优化掉。至少 Mono 的 JIT 是这样做的。从 CIL 的角度来看,它可以很容易地看到发生了什么:

.locals init (int32 i)

ldc.i4.0
stloc.0

// i = 0

br.s loop_test

loop_body:
    ldloc.0
    ldc.i4.1
    add
    stloc.0

    // i = i + 1

loop_test:
    ldloc.0
    ldc.i4.s  10
    blt.s loop_body

    // i < 10  

ret

在 CIL 级别,for 基本上是:

  • 一个预先测试的循环(在第一次执行主体之前测试条件,因此 br,一个无条件分支),
  • 变量循环体之前的初始化器,
  • 对循环体末尾的已初始化变量的操作。

很容易直观地识别上面 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:

.locals init (int32 i)

ldc.i4.0
stloc.0

// i = 0

br.s loop_test

loop_body:
    ldloc.0
    ldc.i4.1
    add
    stloc.0

    // i = i + 1

loop_test:
    ldloc.0
    ldc.i4.s  10
    blt.s loop_body

    // i < 10  

ret

At the CIL level, a for is basically:

  • a pre-tested loop (the condition is tested before the body is first executed, hence the br, an unconditional branch),
  • variable initializers before the loop body,
  • operations on the initialized variables at the end of the body.

It's quite easy to visually identify the different for elements in the CIL above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文