Does using the this
keyword affect Java performance at all?
In this example:
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 it does not.
The code with or without
this
keyword after compilation is exactly the same.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
proves it. Here is with thethis.
:And here is without
this.
:Only difference is the
2
, but I had to choose a different name for the two test cases.