Reputation: 2001
I was wondering the execution speed changes if a programmer concatenates inside a Stringbuilder append() statement, or just uses two append statements instead of one.
I am asking this question to help me figure out why we use the StringBuilder class at all when we can just concatenate.
Concatenation Example:
public class MCVE {
public static void main(String[] args) {
String[] myArray = {"Some", "stuff", "to", "append", "using", "the",
"StringBuilder", "class's", "append()", "method"};
StringBuilder stringBuild = new StringBuilder();
for(String s: myArray) {
stringBuild.append(s + " ");
}
}
}
Double-Append() Example:
public class MCVE {
public static void main(String[] args) {
String[] myArray = {"Some", "stuff", "to", "append", "using", "the",
"StringBuilder", "class's", "append()", "method"};
StringBuilder stringBuild = new StringBuilder();
for(String s: myArray) {
stringBuild.append(s);
stringBuild.append(" ");
}
}
}
Upvotes: 2
Views: 128
Reputation: 1074385
In theory, yes, the concatenation version will take longer, because under the covers it creates a whole new StringBuilder
, appends s
, appends " "
, and then uses toString
to create(!) a string for that to pass to the append
you coded. (That's what the compiler does. To know about your specific situation, you'd need to test a benchmark representative of your actual code. After all, the JIT will get involved if it's a hotspot at runtime.)
Of course, you probably won't notice. But still, if you're already using StringBuilder
, use it (by doing append
twice instead). :-)
(The first paragraph above wouldn't be true if they were both string literals, e.g. "foo" + "bar"
. The compiler does that concatenation.)
Upvotes: 3