6

On Java 1.7+ should we still need to convert "this string" + "should" + "be" + "joined" using StringBuffer.append for best practices?

TommCatt
  • 5,498
  • 1
  • 13
  • 20
kjv.007
  • 93
  • 10
  • Since Java 8 you have the possibility to make a list of Strings you want to be joined and use the static method [String.join](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-). – halex Apr 15 '15 at 05:14
  • 1
    Do you mean `StringBuilder()`? – PM 77-1 Apr 15 '15 at 05:15
  • Actually, there are two classes StringBuffer and StringBuilder, both do concatenation. About the difference between them read: http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer – vk23 Apr 15 '15 at 05:39
  • thanks.. this is very informative. – kjv.007 Apr 15 '15 at 07:42

2 Answers2

10

1) constant expressions (JLS 15.28) like "this string" + " should" + " be" + " joined" do not need StringBuilder because it is calculated at compile time into one string "this string should be joined"

2) for non-constant expressions compiler will apply StringBuilder automatically. That is, "string" + var is equivalent to new StringBuilder().append("string").append(var).toString();

We only need to use StringBuilder explicitly where a string is constructed dynamically, like here

    StringBuilder s = new StringBuilder();
    for (String e : arr) {
        s.append(e);
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1
// using String concatentation
String str = "this string" + "should" + "be" + "joined";

// using StringBuilder
StringBuilder builder = new StringBuilder();
builder.append("this string");
builder.append("should");
builder.append("be");
builder.append("joined");
String str = builder.toString();

Your decision to use raw String concatenation versus StringBuilder is probably going to depend on the readability and maintainability of your code, rather than performance. Under the Oracle JVM, using direct String concatenation, the compiler will actually use a single StringBuilder under the hood. As a result, both examples I gave above would have nearly identical bytecode. If you find yourself doing many series of raw String concatenations, then StringBuilder may offer you a performance improvement. See this article for more information (which was written after Java 7 was released).

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360