Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java static calls more or less expensive than non-static calls?

Is there any performance benefit one way or another? Is it compiler/VM specific? I am using Hotspot.

like image 621
Andy Faibishenko Avatar asked Sep 27 '10 15:09

Andy Faibishenko


People also ask

Which is better static or non-static Java?

A static method cannot be overridden being compile time binding. A non-static method can be overridden being dynamic binding. Static method occupies less space and memory allocation happens once. A non-static method may occupy more space.

Why should we avoid static in Java?

Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.

Are static methods better?

They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.


1 Answers

First: you shouldn't be making the choice of static vs non-static on the basis of performance.

Second: in practice, it won't make any difference. Hotspot may choose to optimize in ways that make static calls faster for one method, non-static calls faster for another.

Third: much of the mythos surrounding static versus non-static are based either on very old JVMs (which did not do anywhere near the optimization that Hotspot does), or some remembered trivia about C++ (in which a dynamic call uses one more memory access than a static call).

like image 132
Anon Avatar answered Sep 21 '22 15:09

Anon