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

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

问题描述

对于Java中的字符串连接,通常最好使用 StringBuilder 。总是这样吗?

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

我的意思是:创建一个 StringBuilder 对象的开销是多少 append()方法,最后 toString()已经小了,然后用连接现有字符串两个字符串的+ 运算符,或者只建议多于两个字符串?

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)?

最后,你会交换 + <的可读性和简洁性吗? / code>在较小的情况下,如两个,三个或四个字符串, StringBuilder 的性能串联?

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?

StringBuilder 进行常规连接已过时-tips>过时的Java优化技巧以及 Java的都市神话的。

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;
}

然后你应该使用 StringBuilder (不是 StringBuffer )而不是 String ,因为它更快,消耗更少的内存。

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

如果你有一个语句,

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

然后你可以使用 String s,因为编译器将自动使用 StringBuilder

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

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

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