0

I noticed there's a performance difference between these two styles of using StringBuilder:

StringBuilder text = new StringBuilder();
// style 1
text.append("a" + "b");
// style 2
text.append("a").append("b");

It seems the more data text append, the less efficient style 1 gets. In fact, style 1 took about twice amount of time compared to style 2 in my stress text. Can someone explain why style 1 is less efficient? Thank you for your help!

edhu
  • 449
  • 6
  • 23
  • 2
    `StringBuilder` is designed to be mutated...`String` objects are not. Every time you concatenate 2 `String`'s together another `String` is created. `String` objects are immutable. – brso05 Sep 12 '16 at 18:15
  • 2
    Note that the assertion in the question will be false for the code in the question, because `"a"` and `"b"` are string literals. The compiler combines them and outputs `append("ab")`. For the assertion to be true, at least one of those needs to be *not* a string literal. – T.J. Crowder Sep 12 '16 at 18:22

2 Answers2

2

Style 1 needs to create an immutable string "ab" to be appended (to StringBuilder). Style 2 appends the string "a" and "b" directly into the StringBuilder.

-1

I believe the reason is because example 1 uses the String class to join the two Strings and then append it to your builder. However when using example two, the String class does not need.To be.used to join, but rather just adds the Strings to your builder.

Part of the reason is because String cannot be changed you cannot change "a" to "ab". A completely new String object is created while Stringbuilder can change its value without creating a new object. See here for info on Stringbuilder vs String

Community
  • 1
  • 1