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

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

+6
source share
2 answers

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

2) StringBuilder is automatically applied to the mutable expression compiler. That is, "string" + var equivalent to new StringBuilder().append("string").append(var).toString();

We only need to explicitly use StringBuilder, where the string is built dynamically, for example here

  StringBuilder s = new StringBuilder(); for (String e : arr) { s.append(e); } 
+10
source
 // 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 will probably depend on the readability and maintainability of your code, and not on performance. Within the framework of the Oracle JVM, using direct String concatenation, the compiler actually uses one StringBuilder under the hood. As a result, both of the examples above would have an almost identical bytecode. If you find yourself doing a lot of serial String concatenation, then StringBuilder can offer you a performance improvement. See this article for more information (which was written after Java 7 was released).

+1
source

Source: https://habr.com/ru/post/985156/


All Articles