Java Post增量与OpCode IINC

发布于 2025-01-28 13:08:54 字数 300 浏览 2 评论 0原文

我们大多数人都熟悉邮政增量,但是当我查看字节码指令时,它表明了增量发生在调用该方法之前。

示例:

int x = 0;
aMethod(x++);

bytecode:

0: iconst_0
1: istore_1
2: iload_1
3: iinc          1, 1
6: invokestatic  #2                  // Method aMethod:(I)V
9: return

有人可以澄清一下吗?

Most of us are familiar with post increment, but when I look to the bytecode instructions, it shows the increment happened before the invocation to the method.

Example:

int x = 0;
aMethod(x++);

bytecode:

0: iconst_0
1: istore_1
2: iload_1
3: iinc          1, 1
6: invokestatic  #2                  // Method aMethod:(I)V
9: return

Can someone clarify this?

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

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

发布评论

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

评论(1

叶落知秋 2025-02-04 13:08:54

多亏了@VOO,

我为比较目的提取了另一个示例:

0: iconst_0
1: istore_1
2: iinc          1, 1
5: iload_1
6: invokestatic  #2                  // Method aMethod:(I)V
9: return

在指令2#和5#中可以看到差异(在ILOAD_1之前调用IINC),而在In Post Incement中,ILOAD_1在IINC之前调用。

这意味着增量将发生在变量本身上,而不是将其推向堆栈的副本上,该副本被用作调用该方法的参数。

来自在这里

iinc

通过常量

增量局部变量

该索引是一个无符号字节,必须是本地的索引
当前帧的变量数组
(§2.6)。 const是直接的
签名字节。索引处的本地变量必须包含一个int。这
Value Const首先将签名扩展到INT,然后是本地
索引的变量被那个数量增​​加。

Thanks to @voo

I've made a another example for pre increment for comparison purpose:

0: iconst_0
1: istore_1
2: iinc          1, 1
5: iload_1
6: invokestatic  #2                  // Method aMethod:(I)V
9: return

The difference can be seen in instruction 2# and 5# (iinc invoked before iload_1), while in in post increment, iload_1 invoked before iinc.

That means the increment will occur on the variable itself and not on the copy pushed onto the stack, which been used as parameter to invoke the method.

from here:

iinc

Increment local variable by constant

The index is an unsigned byte that must be an index into the local
variable array of the current frame
(§2.6). The const is an immediate
signed byte. The local variable at index must contain an int. The
value const is first sign-extended to an int, and then the local
variable at index is incremented by that amount.

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