Overhead of 'this' keyword

code-readability, java, optimization

Solution

None whatsoever. They both produce exactly the same bytecode. For example, this:

package test;

public class T {

    int a=0;

    public T() {
        System.out.println(a); //this line
    }

    public static void main(String[] args) {
        new T();
    }

}

...produces:

public class test.T {
  int a;

  public test.T();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: aload_0       
       5: iconst_0      
       6: putfield      #2                  // Field a:I
       9: getstatic     #3                  // Field     java/lang/System.out:Ljava/io/PrintStream;
      12: aload_0       
      13: getfield      #2                  // Field a:I
      16: invokevirtual #4                  // Method java/io/PrintStream.println:(I)V
      19: return        

  public static void main(java.lang.String[]);
    Code:
       0: new           #5                  // class test/T
       3: dup           
       4: invokespecial #6                  // Method "<init>":()V
       7: pop           
       8: return        
}

...regardless of whether the line marked this line uses `a` or `this.a`. (Try it if you like - compile the above code both ways and compare both class files with `javap -c`.) Considering they produce exactly the same bytecode, there's no way there can be differences in performance.

Problem

This seems like it could be a common question but I searched SO and Google and couldn't find quite what I'm looking for: What is the overhead of calls to the `this` keyword in Java? I know in C++ there is some minimal overhead due to dereferencing the current object pointer. Does Java incur the same kind of overhead? Is it less optimal to make multiple calls to `this`. It's mostly a question of readability vs. optimization.

Original source