Java – calling a method is faster when you initialize an object or save it as a variable and call the method

Suppose there is a classA class that gives the value I need through non - static methods

If I only need the value of one instance of classA, I think there are two possible options

double value =0 ; // The value I actually need,the object is just transitory

1) ClassA a = new ClassA (hogehoge);
   value = a.getValue();

2) value = new ClassA(hogehoge).getValue();

I know these two may have advantages or disadvantages But generally speaking, what is the difference between them?

In case 2), memory usage is less than 1) or

Solution

In fact, there is a difference between the two codes:

***** Class1.p
       8: invokespecial #4                  // Method ClassA."<init>":(Ljava/lang/String;)V
      11: astore_3
      12: aload_3
      13: invokevirtual #5                  // Method ClassA.getValue:()D
      16: dstore_1
      17: dload_1
      18: dreturn
}
***** CLASS2.P
       8: invokespecial #4                  // Method ClassA."<init>":(Ljava/lang/String;)V
      11: invokevirtual #5                  // Method ClassA.getValue:()D
      14: dstore_1
      15: dload_1
      16: dreturn
}
*****

That is, we see two additional variant #1 descriptions here:

11: astore_3
      12: aload_3

However, it seems that after the JVM heats up, these instructions will be optimized (eliminated), which makes no difference at all

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>