StringBuilder vs String concatenation in toString() in Java

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

    The key is whether you are writing a single concatenation all in one place or accumulating it over time.

    For the example you gave, there's no point in explicitly using StringBuilder. (Look at the compiled code for your first case.)

    But if you are building a string e.g. inside a loop, use StringBuilder.

    To clarify, assuming that hugeArray contains thousands of strings, code like this:

    ...
    String result = "";
    for (String s : hugeArray) {
        result = result + s;
    }
    

    is very time- and memory-wasteful compared with:

    ...
    StringBuilder sb = new StringBuilder();
    for (String s : hugeArray) {
        sb.append(s);
    }
    String result = sb.toString();
    
    0 讨论(0)
  • 2020-11-21 04:45

    Can I point out that if you're going to iterate over a collection and use StringBuilder, you may want to check out Apache Commons Lang and StringUtils.join() (in different flavours) ?

    Regardless of performance, it'll save you having to create StringBuilders and for loops for what seems like the millionth time.

    0 讨论(0)
  • 2020-11-21 04:45

    I think we should go with StringBuilder append approach. Reason being :

    1. The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects.

    2. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.

    0 讨论(0)
  • 2020-11-21 04:46

    Make the toString method as readable as you possibly can!

    The sole exception for this in my book is if you can prove to me that it consumes significant resources :) (Yes, this means profiling)

    Also note that the Java 5 compiler generates faster code than the handwritten "StringBuffer" approach used in earlier versions of Java. If you use "+" this and future enhancements comes for free.

    0 讨论(0)
  • 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<n;i++)
              str.append("myBigString");    
      }
      
      private static void usingStringConcatenation(int n)
      {
          String str = "";
          for(int i=0;i<n;i++)
              str+="myBigString";
      }
      

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

    usingStringConcatenation 29321 ms
    usingStringBuilder 2 ms
    
    0 讨论(0)
  • 2020-11-21 04:47

    For simple strings like that I prefer to use

    "string".concat("string").concat("string");
    

    In order, I would say the preferred method of constructing a string is using StringBuilder, String#concat(), then the overloaded + operator. StringBuilder is a significant performance increase when working large strings just like using the + operator is a large decrease in performance (exponentially large decrease as the String size increases). The one problem with using .concat() is that it can throw NullPointerExceptions.

    0 讨论(0)
提交回复
热议问题