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
Regardless of what is faster and how much, there is one major difference that you need to remember:
@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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With