I have a utility class which has non static methods with no instance variables. So I am thinking of converting all the methods to static
methods. I doubt there will be any memory or performance impacts. But I just wanted to confirm.
Will changing such a method to be a static
have any performance impact on the program?
One final thing to add to what people have said here.
Using a static
method has a slightly less overhead due to the fact that you have guaranteed compile time binding. Static method calls will create the bytecode instruction invokestatic
. ]
In a typical scenario, instance methods are bound at runtime, and will create the bytecode instruction invokevirtual
which has higher overhead than invokestatic
.
However, this only becomes relevant in the case of likely millions of iterations, and i would caution against this driving your class design. Do what makes sense from a design perspective. Based on your description, static
methods are probably the way to go. In fact, this is relatively standard practice to create a utility class:
public class MyUtilities {
private MyUtilities() { } // don't let anyone construct it.
public static String foo(String s) { ... }
}
EDIT: Addressing the performance aspect: it's cheaper not to have to create an instance of something pointlessly, but the difference is very likely to be completely irrelevant. Focusing on a clear design is much more likely to be important over time.
Utility methods are frequently static, and if all the methods within a class are static it may well be worth making the class final
and including a private constructor to prevent instantation. Fundamentally, with utility classes which don't represent any real "thing" it doesn't make logical sense to construct an instance - so prevent it.
On the other hand, this does reduce flexibility: if any of these utility methods contain functionality which you may want to vary polymorphically (e.g. for testing purposes) then consider leaving them as instance methods - and try to extract some meaningful class name to represent the "thing" involved. (For example, a FooConverter
makes sense to instantiate - a FooUtil
doesn't.)
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