9

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?

Tux
  • 1,896
  • 3
  • 19
  • 27

2 Answers2

21

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 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
}

And here is without this.:

{
  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
}

Only difference is the 2, but I had to choose a different name for the two test cases.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • Thanks! I haven't used javap before. Like @T.J. Crowder Magic said, I should probably go back to the JLS for a bit and study up on javap, too. – Tux Feb 06 '14 at 23:01
  • Was it always like this? I haven't done Java for the last 10 years or so, but I briefly remember hearing back then, that the use of this was slightly faster due to some optimizations, maybe it was a wrong assumption. – MeTitus Jun 23 '16 at 17:29
  • @MeTitus I heard the opposite, that using this is slightly slower :) but I am not able to find anything performance related to the usage of `this`. Therefore I consider using this as equal to not using it. – scipper Aug 23 '23 at 07:03
0

No it does not.

The code with or without this keyword after compilation is exactly the same.

ciamej
  • 6,918
  • 2
  • 29
  • 39