Java 字符串生成器与字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18453458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:44:14  来源:igfitidea点击:

String builder vs string concatenation

javastringbuilderstring-concatenation

提问by Chun ping Wang

What is the benefit and trade-off of using a string builder over pure string concatenation?

使用字符串构建器而不是纯字符串连接有什么好处和权衡?

new StringBuilder(32).append(str1)
                     .append(" test: ")
                     .append(val)
                     .append(" is changed")
                     .toString();

vs say

vs 说

str1 + " test: " + val + " is changed".

str1is a random 10 character string. str2is a random 8 character string.

str1是一个随机的 10 个字符的字符串。 str2是一个随机的 8 个字符的字符串。

采纳答案by Mario Rossi

In your particular example, none because the compiler internally uses StringBuilders to do String concatenation. If the concatenation occurred in a loop, however, the compiler could create several StringBuilderand Stringobjects. For example:

在您的特定示例中,没有,因为编译器在内部使用StringBuilders 进行字符串连接。但是,如果串联发生在循环中,则编译器可以创建多个StringBuilderandString对象。例如:

String s= "" ;
for(int i= 0 ; i < 10 ; i++ )
    s+= "a" ;

Each time line 3 above is executed, a new StringBuilderobject is created, the contents of sappended, "a" appended, and then the StringBuilderis converted into a String to be assigned back to s. A total of 10 StringBuilders and 10 Strings.

每次执行上面的第 3 行,StringBuilder都会创建一个新对象,将 append 的内容s,“a”附加,然后将StringBuilder转换为 String 以重新分配给s。总共10StringBuilder秒和10String秒。

Conversely, in

相反,在

StringBuilder sb= new StringBuilder() ;
for(int i= 0 ; i < 10 ; i++ )
    sb.append( "a" );
String s= sb.toString() ;

Only 1 StringBuilderand 1 Stringare created.

只创建了1StringBuilder和 1 String

The main reason for this is that the compiler could not be smart enough to understand that the first loop is equivalent to the second and generate more efficient (byte) code. In more complex cases, it's impossible even for the smartest compiler to know. If you absolutely need this optimization, you have to introduce it manually by using StringBuilders explicitly.

这样做的主要原因是编译器不够聪明,无法理解第一个循环与第二个循环等效并生成更高效的(字节)代码。在更复杂的情况下,即使是最聪明的编译器也不可能知道。如果您绝对需要这种优化,则必须通过StringBuilder显式使用s手动引入它。

回答by Mario Rossi

The quick answer is the performance: when you are using native String classes it operates immutable strings, which means when you are writing

快速回答是性能:当您使用本机 String 类时,它操作不可变字符串,这意味着当您编写

  String line = "java";
  String sufix = " is awesome";
  line = line + sufix;

it will create two strings "java" and " is awesome", than create a new third string "java is awesome" from previous two ("java" and "is awesome") which later are likely to be deleted by a garbage collector (because they are no more used in app). That is a slow solution.

它将创建两个字符串“java”和“is awesome”,然后从前两个字符串(“java”和“is awesome”)中创建一个新的第三个字符串“java is awesome”,稍后可能会被垃圾收集器删除(因为它们不再用于应用程序中)。这是一个缓慢的解决方案。

More faster solution is an appliance of StringBuffer class which through the smart algorightms that provide a buffer (that is obvious from its name) for merging strings and as a result would not remove the initial string during the concatenation process.

更快的解决方案是 StringBuffer 类的一个组件,它通过智能算法提供一个缓冲区(从它的名字中可以看出)来合并字符串,因此不会在连接过程中删除初始字符串。

In case you are writing single thread-application (no concurrancy issues during which multiple threads access same object) it is better to apply StringBuilder which has even faster performance than the initial StringBuffer class.

如果您正在编写单线程应用程序(在多个线程访问同一对象期间没有并发问题),最好应用性能比初始 StringBuffer 类更快的 StringBuilder。