Static methods or Singletons on performance (Android)?

In an application with a small number of POJOs and many helper methods that work on them, which is better in performance: do helper classes be single or do static methods?

+7
java performance android static-methods singleton
source share
4 answers

Static methods would be slightly more efficient and sensible from memory:

  • Avoid the (potential) overhead of virtual function calls.
  • Eliminates the memory needed for the actual instance of the class.
  • Eliminates the need to get an instance of the class when using it.

But to be honest, I might still do it singleton anyway. The achievements you get without doing this are probably so small that they will make zero difference, even in a mobile environment.

+9
source share

Can you avoid any situation and make them regular classes?

Ignoring the performance issue, I would recommend avoiding plain and static methods to improve your testability.

Singlets and static methods can be very difficult to test; in this regard, singletones are essentially static methods, but with a different name. Misko Hevery , who is working on the Google Test team , has some good articles on this subject:

+6
source share

Do not worry about absurd micro-optimization. Worry about maintainability.

It looks like this application is written in a completely non-OO style and can greatly benefit from eliminating most of these β€œhelper methods” and placing them where they belong with the data on which they work.

+4
source share

Taking your question at face value, static calls are likely to require the least amount of processor power. The reason is that conventional methods are dynamically related and require some search at runtime, while static methods bind compilation time.

Having said that, it probably doesn't matter in your application. The difference is really small. If your application does anything using gui, xml rendering, Internet connections, or other external manipulations, you will find that these actions overshadow the simple search for mathod by a huge factor.

Even if you do not, during profiling you are more likely to encounter one bottleneck that supports your application, and you will find that this is not a search method, but some kind of logic that you did yourself. For example, you used arraylist instead of hashset, and the contains method turned out to be expensive.

Since performance in these cases is not a big deal, I would recommend using singleton implementations over static methods, as the design is a bit more flexible. Despite the fact that you no matter what you suggested, I completely drop the helper classes and include the methods in your pojo's.

+2
source share

All Articles