StringBuilder vs. String considering replace

DanielGibbs picture DanielGibbs · Feb 11, 2011 · Viewed 33k times · Source

When doing concatenating lots of strings, I have been recommended to do it using a StringBuilder as such:

StringBuilder someString = new StringBuilder("abc");
someString.append("def");
someString.append("123");
someString.append("moreStuff");

as opposed to

String someString = "abc";
someString = someString + "def";
someString = someString + "123";
someString = someString + "moreStuff";

which would result in the creation of quite a few Strings, as opposed to one.

Now, I need to do a similar thing, but instead of using concatenation I use the replace method of String as such:

String someString = SOME_LARGE_STRING_CONSTANT;
someString = someString.replace("$VARIABLE1", "abc");
someString = someString.replace("$VARIABLE2", "def");
someString = someString.replace("$VARIABLE3", "123");
someString = someString.replace("$VARIABLE4", "moreStuff");

To accomplish the same thing using StringBuilder, I have to do this, just for one replace:

someString.replace(someString.indexOf("$VARIABLE1"), someString.indexOf("$VARIABLE1")+10, "abc");

So my question is: "Is it better to use String.replace and have lots of extra Strings created, or to use StringBuilder still, and have lots of long winded lines such as the one above?"

Answer

Zach L picture Zach L · Feb 11, 2011

It is true that StringBuilder tends to be better than concatenating or modifying Strings manually, since StringBuilder is mutable, while String is immutable and you need to create a new String for each modification.

Just to note, though, the Java compiler will automatically convert an example like this:

String result = someString + someOtherString + anotherString;

into something like:

String result = new StringBuilder().append(someString).append(someOtherString).append(anotherString).toString();

That said, unless you're replacing a whole lot of Strings, go for whichever is more readable and more maintainable. So if you can keep it cleaner by having a sequence of 'replace' calls, go ahead and do that over the StringBuilder method. The difference will be negligible compared to the stress you save from dealing with the sad tragedy of micro-optimizations.

PS

For your code sample (which, as OscarRyz pointed out, won't work if you have more than one "$VARIABLE1" in someString, in which case you'll need to use a loop), you could cache the result of the indexOf call in:

someString.replace(someString.indexOf("$VARIABLE1"), someString.indexOf("$VARIABLE1")+10, "abc");

With

int index = someString.indexOf("$VARIABLE1");    
someString.replace(index, index+10, "abc");

No need to search the String twice :-)