Home » Android » java – Static methods or Singletons performance-wise (Android)?

java – Static methods or Singletons performance-wise (Android)?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

Can you avoid either situation and make them regular classes?

Ignoring the performance question, I’d recommend avoiding singeltons and static methods to improve your testability.

Singletons and static methods can be very hard to test; in this regard singletons are essentially static methods but with a different name. Misko Hevery, who works on the Google Test team, has a few good articles on this subject:

Answer:

Don’t worry about absurd micro-optimizations like that. Worry about maintainability.

It sounds like that application is written in a totally non-OO style and could benefit a lot from eliminating most of those “helper methods” and putting them where they belong, with the data they operate on.

Answer:

Taking your question at face value, static calls will probably require the least amount of cpu power. The reason is that normal methods are dynamic bound and require some lookup at runtime while static methods are bound a compile time.

Having said that, it probably won’t matter in your application. The difference is really small. If your application does any thing with gui, xml rendering, internet connections or other external manipulation your’ll find that these activities dwarf the simple mathod lookups by a huge factor.

Even if you don’t, during profiling you are more likely to encounter a single bottleneck holding up your application and discover it is not the method lookup, but some logic you did your self. For example you used an arraylist instead of a hashset and the contains method turn out to be expensive.

So as performance in these cases doesn’t really matter, I would recommend using the singletons implementations above the static methods as the design is slightly more flexible. Though outside the choices you offered I would drop the helper classes entirely and inline the methods in your pojo’s.