Why StringBuilder when there is String?

2019-01-01 05:15发布

I just encountered StringBuilder for the first time and was surprised since Java already has a very powerful String class that allows appending.

Why a second String class?

Where can I learn more about StringBuilder?

9条回答
皆成旧梦
2楼-- · 2019-01-01 05:58

The StringBuilder class is mutable and unlike String, it allows you to modify the contents of the string without needing to create more String objects, which can be a performance gain when you are heavily modifying a string. There is also a counterpart for StringBuilder called StringBuffer which is also synchronized so it is ideal for multithreaded environments.

The biggest problem with String is that any operation you do with it, will always return a new object, say:

String s1 = "something";
String s2 = "else";
String s3 = s1 + s2; // this is creating a new object.
查看更多
大哥的爱人
3楼-- · 2019-01-01 05:59

Here is a concrete example on why -

int total = 50000;
String s = ""; 
for (int i = 0; i < total; i++) { s += String.valueOf(i); } 
// 4828ms

StringBuilder sb = new StringBuilder(); 
for (int i = 0; i < total; i++) { sb.append(String.valueOf(i)); } 
// 4ms

As you can see the difference in performance is significant.

查看更多
泛滥B
4楼-- · 2019-01-01 06:05

String does not allow appending. Each method you invoke on a String creates a new object and returns it. This is because String is immutable - it cannot change its internal state.

On the other hand StringBuilder is mutable. When you call append(..) it alters the internal char array, rather than creating a new string object.

Thus it is more efficient to have:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 500; i ++) {
    sb.append(i);
}

rather than str += i, which would create 500 new string objects.

Note that in the example I use a loop. As helios notes in the comments, the compiler automatically translates expressions like String d = a + b + c to something like

String d = new StringBuilder(a).append(b).append(c).toString();

Note also that there is StringBuffer in addition to StringBuilder. The difference is that the former has synchronized methods. If you use it as a local variable, use StringBuilder. If it happens that it's possible for it to be accessed by multiple threads, use StringBuffer (that's rarer)

查看更多
登录 后发表回答