The reason to prefer StringBuilder is that both + and concat create a new
object every time you call them (provided the right-hand side argument is
not empty). This can quickly add up to a lot of objects, almost all of
which are completely unnecessary.

public class Main{
    public static void main(String[] args)
    {
        long now = System.currentTimeMillis();
        slow();
        System.out.println("slow elapsed " +
(System.currentTimeMillis() - now) + " ms");

        now = System.currentTimeMillis();
        fast();
        System.out.println("fast elapsed " +
(System.currentTimeMillis() - now) + " ms");
    }

    private static void fast()
    {
        StringBuilder s = new StringBuilder();
        for(int i=0;i<100000;i++)
            s.append("*");
    }

    private static void slow()
    {
        String s = "";
        for(int i=0;i<100000;i++)
            s+="*";
    }
}


   - slow elapsed 11741 ms
   - fast elapsed 7 ms

Also, this PR avoids unnecessary call in StringBuilder
Ref: https://github.com/apache/tomee/pull/219

Reply via email to