I am dealing with an application that contains lots of legacy code. What I see very often is string concatenation using "+" within a StringBuilder argument.
Example:
StringBuilder sb = new StringBuilder("This " + "looks " + "rather " + "weird " + "to " + "me.") From what I've learned the compiler replaces a string concatenation that uses the + operator with StringBuilder().append().
I am afraid now the compiler will create a temporary StringBuilder to perform the concatenation then convert toString() and insert the result into the existing StringBuilder.
My Question is: Is the compiler able to optimize the nested StringBuilder away? And if not should I rewrite the code to save a few CPU cycles? It is obviously working but it hurts my eyes whenever I look at it.
Thanks for any insights!
compiler replaces a string concatenation that uses the + operator with StringBuilder().append()? If that was true, we wouldn't care to use StringBuilder or string concatenationStringBuilderallows you to dynamically append (e.g. in a loop). I believe+does use aStringBuilder.+will be implicitly translated to useStringBuilder. Only when concatenating over multiple statements, especially when looping, you should useStringBuilderexplicitly.