String str=""; for (int i = 0; i < count; i++) { str+="я"; } 

it is true that this code turns the compiler into this:

 StringBuilder sb = new StringBuilder(); for (int j = 0; j < i; j++) { sb.append("я"); } 

If so, does it make sense to use the second option? After all, the first is more readable.

    2 answers 2

    Read here .

     //медленно String[] fields = new String[] {"a","b","c","d","e","f","g"}; String s = ""; for (int i = 0; i < fields.length; i++) { s = s + fields[i]; } return s; //быстро String[] fields = new String[] {"a","b","c","d","e","f","g"}; StringBuilder s = new StringBuilder(); for (int i = 0; i < fields.length; i++) { s.append(fields[i]); } return s.toString(); 

    Never use concatenation operations (operator +) strings in a loop, especially if you have many such operations, this can significantly reduce performance. All this happens because in the above example, “s = s + fileds [i]” performs as many as 3 operations: a StringBuilder is created based on the string s, the append concatenation method is called, and the toString method is called after concatenation (s = new StringBuilder (s) .append (fields [i]). toString ();). As many as 3 operations instead of one! In addition, each result s + fileds [i] will occupy the memory in the heap, as a separate line.

    So the answer to your question is: yes, it makes sense to use StringBuilder instead of concatenation.

    • I saw one of Shipilev's reports, and there he gave an example of when he would use + more quickly. Although perhaps I did not interpret it that way - Andrew Bystrov
    • @AndrewBystrov, maybe it was about iterators?) Automation-remarks.com/… - Ksenia

    In the first variant, the loop will create count strings, which may be deleted by the garbage collector, which is not good. The second case is much better because it does not create a new object, as String does, but adds the necessary characters to the existing string, which saves memory and prevents the garbage collector from deleting. I strongly recommend using it. But it is worth remembering that this class is not synchronized, so you should not use it in multi-threaded applications, but replace it with the StringBuffer class, which is almost identical to StringBuilder ' , Just a little slower.