Search code examples
javamicro-optimization

Any difference in the performance of these two Java segments?


I'm curious to know if either of these two Java method invocations will behave differently at all in terms of processor time, memory allocation and/or garbage collection.

SomeObject myObj = new SomeObject();
myObj.doSomething();

vs.

new SomeObject().doSomething();

Solution

  • Looking at the generated bytecode:

    // code 1
    new SomeObject().doSomething();
    
    // bytecode 1
       0:   new #2; //class SomeObject
       3:   dup
       4:   invokespecial   #3; //Method SomeObject."<init>":()V
       7:   invokevirtual   #4; //Method SomeObject.doSomething:()V
       10:  return
    

    You can clearly see that this one has two more instructions:

    // code 2
    SomeObject myObj = new SomeObject();
    myObj.doSomething();
    
    // bytecode 2
       0:   new #2; //class SomeObject
       3:   dup
       4:   invokespecial   #3; //Method SomeObject."<init>":()V
       7:   astore_1
       8:   aload_1
       9:   invokevirtual   #4; //Method SomeObject.doSomething:()V
       12:  return
    

    Those instructions seem very redundant and easy to optimize-out. I'd bet the JIT compiler would handle them if needed.