Performance of using static methods vs instantiating the class containing the methods

Solution 1:

From here, a static call is 4 to 5 times faster than constructing an instance every time you call an instance method. However, we're still only talking about tens of nanoseconds per call, so you're unlikely to notice any benefit unless you have really tight loops calling a method millions of times, and you could get the same benefit by constructing a single instance outside that loop and reusing it.

Since you'd have to change every call site to use the newly static method, you're probably better spending your time on gradually refactoring.

Solution 2:

I have dealt with a similar problem where i work. The programmer before me created 1 controller class where all the BLL functions were dumped.

We are redesigning the system now and have created many Controller classes depending on what they are supposed to control e.g.

UserController, GeographyController, ShoppingController...

Inside each controller class they have static methods which make calls to cache or the DAL using the singleton pattern.

This has given us 2 main advantages. It is slightly faster(around 2-3 times faster but were talking nanoseconds here ;P). The other is that the code is much cleaner

i.e

ShoppingController.ListPaymentMethods()

instead of

new ShoppingController().ListPaymentMethods()

I think it makes sense to use static methods or classes if the class doesn't maintain any state.

Solution 3:

It depends on what else that object contains -- if the "object" is just a bunch of functions then it's probably not the end of the world. But if the object contains a bunch of other objects, then instantiating it is gonna call all their constructors (and destructors, when it's deleted) and you may get memory fragmentation and so on.

That said, it doesn't sound like performance is your biggest problem right now.