Note that there are some explanatory texts on larger screens.

plurals
  1. POBest practices/performance: mixing StringBuilder.append with String.concat
    text
    copied!<p>I'm trying to understand what the best practice is and why for concatenating string literals and variables for different cases. For instance, if I have code like this</p> <pre><code>StringBuilder sb = new StringBuilder("AAAAAAAAAAAAA") .append(B_String).append("CCCCCCCCCCC").append(D_String) .append("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE") .append("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); </code></pre> <p>Is this the way to do it? From <a href="https://stackoverflow.com/questions/47605/java-string-concatenation">this post</a>, I noticed that the <code>+</code> operator on Strings creates a new instance of StringBuilder, concatenates the operands, and returns a String conversion, which seems like a lot more work than just calling <code>.append()</code>; so if that's true, then that is out of the question. But what about <code>String.concat()</code>? Is it proper to use <code>.append()</code> for every concatenation? Or just for variables, and literals are okay to append with <code>.concat()</code>?</p> <pre><code>StringBuilder sb = new StringBuilder("AAAAAAAAAAAAA") .append(B_String.concat("CCCCCCCCCCC")).append(D_String .concat("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE") .concat("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")); </code></pre> <p>What are the general rules for best practices and performance for going about these situations? Is my assumption correct on <code>+</code> and it should really just not be used?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload