Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class methods vs instance methods

Hi Are class methods generally measured to be faster than instance methods since it doesn't require loading an instance? If so, should we use class methods when possible? Thanks

like image 956
Niklas Rosencrantz Avatar asked Jul 01 '11 09:07

Niklas Rosencrantz


2 Answers

Regardless of what is faster and how much, there is one major difference that you need to remember:

  • You cannot @Override a static method!

This is very important because you essentially say that you will not, and cannot, use one of the major advantages in Java, namely overriding methods in sub-classed objects. When you call a static method, you stay with that static method and cannot override it in sub-classed objects.

Also to resolve the "which is faster" then construct a REAL test, not just a microbenchmark to investigate the actual findings. Use several JVM's to measure because JIT implementation may influence this.

like image 90
Thorbjørn Ravn Andersen Avatar answered Oct 20 '22 03:10

Thorbjørn Ravn Andersen


If a method doesn't require an instance, IMO it should be a class method. And since a class method is only possible if you don't use the instance, then your question

should we use class methods when possible

has a positive answer.

But definitely NOT for efficiency reasons

like image 20
Armen Tsirunyan Avatar answered Oct 20 '22 01:10

Armen Tsirunyan