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?"