What is better to use for Exception output message dynamic generation String or StringBuilder or StringBuffer?
views:
58answers:
2StringBuffer
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).
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.