How to find all naive ("+" based) string concatenations in large Java codebase?

java, optimization, string

Solution

Just make sure you really understand where it's actually better to use `StringBuilder`. I'm not saying you don't know, but there are certainly plenty of people who would take code like this:

String foo = "Your age is: " + getAge();

and turn it into:

StringBuilder builder = new StringBuilder("Your age is: ");
builder.append(getAge());
String foo = builder.toString();

which is just a less readable version of the same thing. Often the naive solution is the best solution. Likewise some people worry about:

String x = "long line" + 
    "another long line";

when actually that concatenation is performed at compile-time.

As nsander's quite rightly said, find out if you've got a problem first...

Problem

We have a huge code base and we suspect that there are quite a few "+" based string concats in the code that might benefit from the use of StringBuilder/StringBuffer. Is there an effective way or existing tools to search for these, especially in Eclipse? A search by "+" isn't a good idea since there's a lot of math in the code, so this needs to be something that actually analyzes the code and types to figure out which additions involve strings.

Original source