tags:

views:

58

answers:

2

What is better to use for Exception output message dynamic generation String or StringBuilder or StringBuffer?

+7  A: 

StringBuffer has been mostly replaced with StringBuilder, which is faster because it's not synchronized. String is fine unless you are doing a lot of concatenation.

Since you're asking this in the context of Exception message generation, I'd say keep it simple and use String. Well-designed systems shouldn't throw Exception so often that the performance benefit of StringBuilder/StringBuffer matters.

That is, the frequency of exceptions should be low enough that how the detailed message is constructed has little effect on overall performance. "Premature optimization is the root of all evil". Only optimize sections that need it, based on profiling.

If your code spends significant amount of time dynamically generating String for Exception, then there's something really wrong with your design. Optimizing that part of the process wouldn't do much good because exceptions are costly to construct anyway (e.g. the stack trace capture portion).

polygenelubricants
Are you saying well designed systems shouldn't throw exceptions or are you saying they should throw a class that inherits from Exception?... or something else entirely?
Spencer Ruport
I'm saying that frequency of exceptions should be low enough that how the detailed message is constructed has little effect on overall performance.
polygenelubricants
As of Java6, String concatenation is basically same as using StringBuilder (I believe they actually compile it into StringBuilder). (Yes, I've measured it)
Enno Shioji
@Zwei: we're talking about something like `s += appendant;` in a loop. This is quadratic.
polygenelubricants
@polygenelubricants: My understanding was that even that will be compiled into `StringBuilder sb = new StringBuilder(); for(;;){ sb.append(appendant) }` equivalent .. Well I didn't tested this specific case though.
Enno Shioji
A: 

Either String or StringBuilder is fine -- whichever makes the code the most readable. (This isn't code you expect to run often, and presumably it doesn't involve long loops or deep recursion.)

StringBuffer is unnecessary unless it's going to be accessed from multiple threads -- and if you're writing a multi-threaded exception message generator, you don't need help from me and also I would like you to stay a long way away. :)

Depending on what you're putting in those messages and what you plan to do with it, consider subclassing Exception in a way that includes separate fields for separate bits of information. For instance, Java 7 NIO's InvalidPathException takes three arguments: the original bad input, the reason the input was invalid, and the index of the error -- enough to let you construct a detailed, nicely formatted error display.

David Moles