Do accessor methods contribute to performance in a non-stationary way?

Assuming all method calls here are static, e.g .:

public class Util {
    public static void method1() {
    }
}

      

Static path access:

Util.method1();
Util.method2();
Util.method3();

      

non-stationary access

Util util = new Util();
util.method1();
util.method2();
util.method3();

      

Is there a performance difference anyway? I know the first way to do it here is to access it properly. But the second way only instantiates the util object once, not three times. I can't find anything that points to something other than how to properly access these methods. From what I can tell, there is no functional difference, but a logical difference. Look for some value and benefit anyway if anyone knows.

+3


source to share


2 answers


Is there a performance difference anyway?

Yes - the second is slightly slower due to the creation of a meaningless instance.

I know the first way to do it here is to access it properly. But the second way only instantiates the util object once, not three times.

No, the second way creates one instance Util

, whereas the first way doesn't create any instances.

The first method is significantly better because it makes it clear that this is a static method. Consider this code:



Thread t = new Thread(someRunnable);
t.start();
t.sleep(1000);

      

What does the last call look like? Surely this puts the new thread to sleep, right? No ... it just calls Thread.sleep()

, which only ever makes the current thread sleep.

When you make a call to a static method to act "through" a link, the value of the link is completely ignored - it may even be null:

Util util = null;
util.method1(); // This will still work...

      

+12


source


There is no difference for the code you show as these methods are all static. (However, the compiler will issue a warning for the second group.) I think there is a slight performance advantage for static methods. The bytecode for static access, invokeSpecial, I think should be faster than invokeVirtual, which should do a specific type of decoding.



But this is not enough to worry. Use whatever type of method (static or instance) suits your design. Don't try to optimize method calls like this.

0


source







All Articles