StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2193
北恋
北恋 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:46

    Here is what I checked in Java8

    • Using String concatenation
    • Using StringBuilder

      long time1 = System.currentTimeMillis();
      usingStringConcatenation(100000);
      System.out.println("usingStringConcatenation " + (System.currentTimeMillis() - time1) + " ms");
      
      time1 = System.currentTimeMillis();
      usingStringBuilder(100000);
      System.out.println("usingStringBuilder " + (System.currentTimeMillis() - time1) + " ms");
      
      
      private static void usingStringBuilder(int n)
      {
          StringBuilder str = new StringBuilder();
          for(int i=0;i

    It's really a nightmare if you are using string concatenation for large number of strings.

    usingStringConcatenation 29321 ms
    usingStringBuilder 2 ms
    

提交回复
热议问题