Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods or Singletons performance-wise (Android)?

In an app with a small number of POJOs and lots of helper methods that operate on them, what's better performance-wise: to make the helper classes singletons or to make the methods static?

like image 611
yanchenko Avatar asked Feb 27 '09 15:02

yanchenko


People also ask

Does static methods improve performance?

They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.

Which one should I choose static or singleton pattern?

The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members).

Are static methods singletons?

The singleton, like any other instance of a class, lives on the heap. To its advantage, a huge singleton object can be lazily loaded whenever required by the application. On the other hand, a static class encompasses static methods and statically bound variables at compile time and is allocated on the stack.

What is static method in Android?

The static method is similar to instance or class method of a class but with the difference that the static method can be called through the name of class without creating any instance of that class. A static method is also called class method as it is related with a class and not with individual instance of the class.


1 Answers

Static methods would be very slightly better performance and memory wise:

  1. Avoid (potential) overhead of virtual function calls.
  2. Eliminates memory needed for an actual instance of the class.
  3. Eliminates need to get an instance of the class when you use it.

But honestly I'd probably still make it a singleton anyways. The gains you'd get by not doing it are likely so small that they would make zero difference, even in a mobile environment.

like image 188
Eric Petroelje Avatar answered Oct 31 '22 23:10

Eric Petroelje