字符串生成器与字符串连接 [英] String builder vs string concatenation

查看:103
本文介绍了字符串生成器与字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

str1 is a random 10 character string. str2 is a random 8 character string.

推荐答案

在你的简单例子中,没有,因为编译器使用 StringBuilder 来进行字符串连接。但是,如果连接发生在循环中,则编译器可以创建多个 StringBuilder String 对象。例如:

In your trivial example, none because the compiler uses StringBuilder to do String concatenation. If the concatenation occurred in a loop, however, the compiler could create several StringBuilder and String objects. For example:

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

每执行上面的第3行, StringBuilder 创建对象,附加 s 的内容,附加a,然后将 StringBuilder 转换为要分配回 s 的字符串。总共10 StringBuilder s和10 字符串 s。

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

相反,在

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

仅1 StringBuilder 和1 字符串已创建。

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

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.

这篇关于字符串生成器与字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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