编辑:即使是编译器做这个改变(我不知道),使用字符串连接比使用 StringBuilder 更慢。(错误 =>不,编译器不使用 StringBuilder/StringBuffer)。您只需创建一个简单的基准就可以对其进行测试。+ 运算符在 Java 中为字符串“重载”,但该语言不支持运算符重载。
尝试这样的事情来测试 StringBuilder/StringBuffer 的东西:
String str = "";
StringBuffer sbf = new StringBuffer();
StringBuilder sb = new StringBuilder();
int nTests = 100;
int nConcats = 1000;
long initialTime = 0L;
long afterStrTime = 0L;
long afterSbfTime = 0L;
long afterSbTime = 0L;
for ( int i = 0; i < nTests; i++ ) {
initialTime = System.currentTimeMillis();
str = "";
sbf = new StringBuffer();
sb = new StringBuilder();
for ( int j = 0; j < nConcats; j++ ) {
str += "foo"; // or str = str + "foo"
}
afterStrTime = System.currentTimeMillis();
for ( int j = 0; j < nConcats; j++ ) {
sbf.append( "foo" );
}
afterSbfTime = System.currentTimeMillis();
for ( int j = 0; j < nConcats; j++ ) {
sb.append( "foo" );
}
afterSbTime = System.currentTimeMillis();
}
System.out.printf( "%d milliseconds to perform %d concatenations on String\n", afterStrTime - initialTime, nConcats );
System.out.printf( "%d milliseconds to perform %d concatenations on StringBuilder\n", afterSbfTime - afterStrTime, nConcats );
System.out.printf( "%d milliseconds to perform %d concatenations on StringBuffer\n", afterSbTime - afterSbfTime, nConcats );
你会看到 StringBuilder 可以比 StringBuffer 快,因为它不是同步的(StringBuffer 是),而且两者都比 String 快。