Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:</p> <pre><code>String a = "a" + "b" + "c"; String b = System.getProperty("blah") + "b"; </code></pre> <p>The first is evaluated at <strong>compile-time</strong>. The second is evaluated at <strong>run-time</strong>.</p> <p>So <strong>never</strong> replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.</p> <p>If the characters are constant, this is fine:</p> <pre><code>String s = "" + 'a' + 'b' + 'c'; </code></pre> <p>If however they aren't, consider this:</p> <pre><code>String concat(char... chars) { if (chars.length == 0) { return ""; } StringBuilder s = new StringBuilder(chars.length); for (char c : chars) { s.append(c); } return s.toString(); } </code></pre> <p>as an appropriate solution.</p> <p>However some might be tempted to optimise:</p> <pre><code>String s = "Name: '" + name + "'"; // String name; </code></pre> <p>into this:</p> <pre><code>String s = new StringBuilder().append("Name: ").append(name).append("'").toString(); </code></pre> <p>While this is well-intentioned, the bottom line is <strong>DON'T</strong>.</p> <p>Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.</p> <p><strong>For low-level optimisation the compiler is better at optimising code than you are.</strong></p> <p>Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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