Does using the 'this' keyword affect Java performance?

前端 未结 2 1451
攒了一身酷
攒了一身酷 2021-01-11 22:59

Does using the this keyword affect Java performance at all?

In this example:

class Prog {
  private int foo;

  Prog(int foo) {
    this         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 23:33

    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."":()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."":()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.

提交回复
热议问题