views:

2228

answers:

4

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?

+5  A: 

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

  1. Avoids (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.

Eric Petroelje
+6  A: 

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:

matt b
+2  A: 

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.

DefLog
+3  A: 

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.

Michael Borgwardt
Okay, then JDK is written in non-OO style as well with all of it's Arrays.sort(), Long.valueOf(), etc. ;)
alex
There's a big difference between having a static method here and there, and having your entire app composed of nothing but value objects and all logic in static methods (which may not be really the case, but that's how you made it sound).
Michael Borgwardt