使用'this'关键字会影响Java性能吗? [英] Does using the 'this' keyword affect Java performance?
问题描述
使用这个
关键字是否会影响Java性能?
Does using the this
keyword affect Java performance at all?
在此示例中:
class Prog {
private int foo;
Prog(int foo) {
this.foo = foo;
}
}
在以下情况下是否存在性能开销?:
Is there performance overhead doing that over the following?:
class Prog {
private int foo;
Prog(int bar) {
foo = bar;
}
}
今天早些时候我和几位同事正在讨论这个问题没有人能拿出我们都同意的答案。任何明确的答案?
A couple of coworkers and I were discussing this earlier today and no one could come up with an answer the we all agreed on. Any definitive answer?
推荐答案
不,完全没有。对于同一件事,它只是一种不同的语法。它被编译成完全相同的字节码。所以说它就像一个人:你用两种不同的方式告诉编译器两次完全相同的事情。
No, not at all. It is just a different syntax for the same thing. It gets compiled into exactly the same piece of bytecode. So say it like a human: you are telling the compiler twice exactly the same thing what to do, in two different ways.
javap
证明了这一点。这是这个。
:
javap
proves it. Here is with the this.
:
{
Prog(int);
flags:
Code:
stack=2, locals=2, args_size=2
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: iload_1
6: putfield #2 // Field foo:I
9: return
LineNumberTable:
line 4: 0
line 5: 4
line 6: 9
}
这里没有这个。
:
{
Prog2(int);
flags:
Code:
stack=2, locals=2, args_size=2
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: iload_1
6: putfield #2 // Field foo:I
9: return
LineNumberTable:
line 4: 0
line 5: 4
line 6: 9
}
唯一的区别是 2
,但我必须为这两个测试用例选择不同的名称。
Only difference is the 2
, but I had to choose a different name for the two test cases.
这篇关于使用'this'关键字会影响Java性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!