What is the difference between using the StringBuilder class in Java's toString() method and using the string connection operator?

Asked 2 years ago, Updated 2 years ago, 177 views

Which of the two toString() methods below is the better one?

public String toString(){
    return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
public String toString(){
    StringBuilder sb = new StringBuilder(100);
    return sb.append("{a:").append(a)
          .append(", b:").append(b)
          .append(", c:").append(c)
          .append("}")
          .toString();
}

More importantly, if you want to create a string with only three field values without any addition, I want to know which method is better.

stringbuilder java string performance concatenation

2022-09-22 15:43

1 Answers

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.