06 July 2009

Putting it together

We've been code-reviewing some of the Java code on the project, and the question of optimal string concatenation came up. While others on the team were loyal to StringBuilder.append(), I had relied on the + operator, following the advice of Ian Darwin in his Java Cookbook 2/e:

3.4.1. Problem

You need to put some String pieces (back) together.

3.4.2. Solution

Use string concatenation: the + operator. The compiler implicitly constructs a StringBuilder for you and uses its append( ) methods. Better yet, construct and use it yourself.

I scratched a little deeper, and found that a more complete answer to "which is better?" depends in part on what compiler optimizations you're using, as Apurba and Pavitar point out. Schneide Blog also notes that it's hard to measure string concatenation performance in isolation from the real-world context where you're performing the operation.

Another point to keep in mind: what are we trying to optimize? Run-time speed, memory usage, or something else? Nicholas Hagen, in his benchmarking tests, helpfully provides both execution times and object creation counts. Hagen gives some rules of thumb. I have added emphasis to the most important one for us, and fortunately it matches our informal shop standards.


  • DO use the plus operator if all operands are constants

  • DO use String.concat if only concatenating 2 strings

  • DO use StringBuilder within a for loop when updating values

  • DO use StringBuilder if concatenating more than 2 strings

  • DO use StringBuilder rather than re-assigning variables multiple times

  • DO ensure StringBuilder has proper sizing



Fortunately for this project, all the Java string manipulation is done in backend systems on an moderate-volume intranet, so these general guidelines are sufficient; we haven't needed to do extensive profiling to find hot spots. The public-facing web site uses different technology altogether.

No comments: