Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>What we know, is that the mutation of a String uses lots of memory.</p> </blockquote> <p>That is incorrect. Strings <strong>cannot</strong> be mutated. They are immutable.</p> <p>What you are actually talking about is building a String from other strings. That can use a lot more memory than is necessary, but it depends <em>how</em> you build the string.</p> <blockquote> <p>So what we can do is to use a StringBuilder/StringBuffer.</p> </blockquote> <p>Using a StringBuilder will help in some circumstances:</p> <pre><code> String res = ""; for (String s : ...) { res = res + s; } </code></pre> <p>(If the loop iterates many times then optimizing the above to use a StringBuilder <em>could</em> be worthwhile.)</p> <p>But in other circumstances it is a waste of time:</p> <pre><code> String res = s1 + s2 + s3 + s4 + s5; </code></pre> <p>(It is a waste of time to optimize the above to use a StringBuilder because the Java compiler will automatically translate the expression into code that creates and uses a StringBuilder.)</p> <p>You should only ever use a StringBuffer instead of a StringBuilder when the string needs to be accessed and/or updated by more than one thread; i.e. when it <em>needs</em> to be thread-safe.</p> <blockquote> <p>But at what point should we change to StringBuilder?</p> </blockquote> <p>The simple answer is to <em>only</em> do it when the profiler <em>tells you</em> that you have a performance problem in your string handling / processing.</p> <p>Generally speaking, StringBuilders are used for <em>building</em> strings rather as the primary representation of the strings.</p> <blockquote> <p>And what should we do, when we have to split it or to replace characters in there?</p> </blockquote> <p>Then you have to review your decision to use a StringBuilder / StringBuffer as your primary representation at that point. And if it is still warranted you have to figure out how to do the operation using the API you have chosen. (This may entail converting to a String, performing the operation and then creating a new StringBuilder from the result.)</p>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      1. This table or related slice is empty.
    2. 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