views:

103

answers:

2

I've got a list of BigDecimals to sum. If they were Strings to concatenate, I would use StringBuilder to reduce object creation. Is there something similar for BigDecimal? Or maybe I shouldn't bother about it? Is optimization of BigDecimal creation worth putting effort to it?

BigDecimal result = BigDecimal.ZERO;
for (CashReportElement element : getReportElementSet()) {
    if (element.getCurrencyCode().equals(currencyCode)) {
     result = result.add(element.getSum());
    }
}
return result;
+7  A: 

I'd cite Donald Knuth here:

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

Don't worry until it really is a measurable (!) problem. I'm not an expert for BigDecimal performance, but copying of char[] which is done during String concatenation is a much bigger overhead, that's for sure.

sfussenegger
+7  A: 

The is no such analog in Java SE.

And on the question if its worth putting effort in it: You should look into this only if this code has been proven to be a performance bottleneck.

Joachim Sauer