有 String 时为什么是 StringBuilder? [英] Why StringBuilder when there is String?

查看:27
本文介绍了有 String 时为什么是 StringBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次遇到 StringBuilder 并且很惊讶,因为 Java 已经有一个非常强大的 String 类允许附加.

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

为什么要使用第二个 String 类?

Why a second String class?

在哪里可以了解有关 StringBuilder 的更多信息?

Where can I learn more about StringBuilder?

推荐答案

String 不允许追加.您在 String 上调用的每个方法都会创建一个新对象并返回它.这是因为 String 是不可变的——它不能改变它的内部状态.

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.

另一方面 StringBuilder 是可变的.当您调用 append(..) 时,它会更改内部字符数组,而不是创建新的字符串对象.

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

因此更有效率:

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

而不是 str += i,后者会创建 500 个新的字符串对象.

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

请注意,在示例中我使用了循环.正如 helios 在注释中指出的那样,编译器会自动将诸如 String d = a + b + c 之类的表达式转换为类似

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();

还要注意,除了 StringBuilder 之外,还有 StringBuffer.不同之处在于前者具有同步方法.如果将其用作局部变量,请使用 StringBuilder.如果碰巧有可能被多个线程访问,使用StringBuffer(这种情况比较少见)

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)

这篇关于有 String 时为什么是 StringBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆