Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance of static vs non static method for an utility class

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?

like image 482
PrabhaT Avatar asked Nov 08 '12 12:11

PrabhaT


2 Answers

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) { ... }
}
like image 172
Matt Avatar answered Sep 19 '22 01:09

Matt


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.)

like image 28
Jon Skeet Avatar answered Sep 19 '22 01:09

Jon Skeet