Difference between StringBuilder and StringBuffer

后端 未结 30 2400
独厮守ぢ
独厮守ぢ 2020-11-21 15:06

What is the main difference between StringBuffer and StringBuilder? Is there any performance issues when deciding on any one of these?

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 15:30

    StringBuilder is faster than StringBuffer because it's not synchronized.

    Here's a simple benchmark test:

    public class Main {
        public static void main(String[] args) {
            int N = 77777777;
            long t;
    
            {
                StringBuffer sb = new StringBuffer();
                t = System.currentTimeMillis();
                for (int i = N; i --> 0 ;) {
                    sb.append("");
                }
                System.out.println(System.currentTimeMillis() - t);
            }
    
            {
                StringBuilder sb = new StringBuilder();
                t = System.currentTimeMillis();
                for (int i = N; i > 0 ; i--) {
                    sb.append("");
                }
                System.out.println(System.currentTimeMillis() - t);
            }
        }
    }
    

    A test run gives the numbers of 2241 ms for StringBuffer vs 753 ms for StringBuilder.

提交回复
热议问题