在 java 字节码中,为什么首先将接收者压入堆栈,然后是所有参数?我记得好像和效率有关。
对于方法调用和设置字段都是如此。
方法调用
class X {
int p(int a) {
//Do something
}
int main() {
int ret = p(1);
}
}
Main 方法编译为:
aload_0 // Load this onto the stack
iconst_1 // Load constant 1 onto the stack
invokevirtual <int p(int)> from class X
设置字段:
class X {
int x;
int main() {
x = 1;
}
}
Main 方法编译为:
aload_0 // Load this onto the stack
iconst_1 // Load constant 1 onto the stack
putfield <int x> from class X
最佳答案
先推有优势
- 目标方法可以使用更密集的“aload0”字节码(小于 如果它在参数列表的后面很多并且不得不使用 aload 字节码的参数版本。因为“this”经常在方法中被引用以访问字段和方法,所以它会带来真正的代码密度改进。
- 人们经常使用级联方法发送,例如“foo.bar().baz()”。当 bar() 返回时, .baz() 的 future “this”神奇地已经在正确的位置 如果您像在 Java 中那样安排事情,请堆栈。
关于this 和堆栈上的参数的 Java 字节码顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10565921/