限定方法调用是否会降低 Java 的性能?
我猜测以下两个函数会编译为完全相同的字节码,但我想问这个问题。在不必要的地方限定方法调用是否会降低性能?
例如:
package com.my;
import android.app.Activity;
import android.os.Bundle;
public class Main extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.setContentView(R.layout.main); // Fully qualified
setContentView(R.layout.main); // Not fully qualified
}
}
标准是使用后者,但是完全限定的调用 this.setContentView()
有任何负面影响吗?
I'm guessing the following two functions compile to the exact same byte-code, but I beg to ask the question. Does qualifying a method call where it is not necessary degrade performance?
For example:
package com.my;
import android.app.Activity;
import android.os.Bundle;
public class Main extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.setContentView(R.layout.main); // Fully qualified
setContentView(R.layout.main); // Not fully qualified
}
}
The standard is to use the latter, but does the fully qualified call this.setContentView()
have any negative effects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有任何惩罚。这两个调用都会在字节码中使用
invokespecial
来调用成员方法。在标准 Java 中,以下代码:
产生以下字节码:
如您所见,两个调用是相同的。
现在,Android 使用 dx 工具将 .class 文件转换为 dalvik 字节码,该工具输出 .dex 文件。由于
.class
文件在两次调用之间没有显示任何区别,因此相应的.dex
文件也不会显示任何差异:您可以看到这两个调用都是使用
直接调用
。因此这里也不存在性能损失。No, there isn't any sort of penalty. Both calls will use
invokespecial
in the bytecode to invoke the member method.In standard Java, the following code:
yields the following bytecode:
As you can see, both calls are the same.
Now Android converts the
.class
files into dalvik bytecode using thedx
tool, which outputs.dex
files. Since the.class
files don't show any distinction between the two invocations, the corresponding.dex
file will show no difference either:You can see that both calls are made using
invoke-direct
. Hence there is no performance penalty here either.不,没有。对于编译器来说都是一样的。使用
this
参考可以被视为阅读帮助,就像 java7 数字文字No it doesn't. It's all the same for the compiler. Using
this
reference may be seen as a reading help, like the underscores in the java7 number literals