StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2255
北恋
北恋 2020-11-21 04:18

Given the 2 toString() implementations below, which one is preferred:

public String toString(){
    return \"{a:\"+ a + \", b:\" + b + \", c: \"         


        
18条回答
  •  遇见更好的自我
    2020-11-21 04:57

    In most cases, you won't see an actual difference between the two approaches, but it's easy to construct a worst case scenario like this one:

    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+="*";
        }
    }
    

    The output is:

    slow elapsed 11741 ms
    fast elapsed 7 ms
    

    The problem is that to += append to a string reconstructs a new string, so it costs something linear to the length of your strings (sum of both).

    So - to your question:

    The second approach would be faster, but it's less readable and harder to maintain. As I said, in your specific case you would probably not see the difference.

提交回复
热议问题