何时在 Java 中使用 StringBuilder [英] When to use StringBuilder in Java

查看:34
本文介绍了何时在 Java 中使用 StringBuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中通常最好使用 StringBuilder 进行字符串连接.总是这样吗?

我的意思是:是创建StringBuilder 对象、调用append() 方法和最后toString() 的开销已经更小然后使用 + 运算符连接两个字符串的现有字符串,还是仅建议用于多个(超过两个)字符串?

如果有这样的阈值,它取决于什么(可能是字符串长度,但以哪种方式)?

最后,在两个、三个或四个字符串等较小的情况下,您会用 + 连接的可读性和简洁性来换取 StringBuilder 的性能吗?>

已废弃Java 优化技巧以及Java城市神话.

解决方案

如果你在循环中使用字符串连接,像这样,

String s = "";for (int i = 0; i <100; i++) {s += ", " + i;}

那么你应该使用 StringBuilder(不是 StringBuffer)而不是 String,因为它更快并且消耗更少的内存.

如果你只有一个语句,

String s = "1, " + "2, " + "3, " + "4, " ...;

那么你可以使用Strings,因为编译器会自动使用StringBuilder.

It is supposed to be generally preferable to use a StringBuilder for string concatenation in Java. Is this always the case?

What I mean is this: Is the overhead of creating a StringBuilder object, calling the append() method and finally toString() already smaller then concatenating existing strings with the + operator for two strings, or is it only advisable for more (than two) strings?

If there is such a threshold, what does it depend on (perhaps the string length, but in which way)?

And finally, would you trade the readability and conciseness of the + concatenation for the performance of the StringBuilder in smaller cases like two, three or four strings?

Explicit use of StringBuilder for regular concatenations is being mentioned as obsolete at obsolete Java optimization tips as well as at Java urban myths.

解决方案

If you use String concatenation in a loop, something like this,

String s = "";
for (int i = 0; i < 100; i++) {
    s += ", " + i;
}

then you should use a StringBuilder (not StringBuffer) instead of a String, because it is much faster and consumes less memory.

If you have a single statement,

String s = "1, " + "2, " + "3, " + "4, " ...;

then you can use Strings, because the compiler will use StringBuilder automatically.

这篇关于何时在 Java 中使用 StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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