更快:
public class ScratchPad {
private static String a;
public static void main( String[] args ) throws Exception {
final long time = System.currentTimeMillis();
// Pre-allocate enough space to store all appended strings.
// StringBuilder, ultimately, uses an array of characters.
final StringBuilder sb = new StringBuilder( 128 );
for( int i = 0; i < 10000000; i++ ) {
// Resetting the string is faster than creating a new object.
// Since this is a critical loop, every instruction counts.
sb.setLength( 0 );
sb.append( "someString" );
sb.append( "someString2" );
sb.append( "someStrin4g" );
sb.append( "someStr5ing" );
sb.append( "someSt7ring" );
setA( sb.toString() );
}
System.out.println( System.currentTimeMillis() - time );
}
private static void setA( final String aString ) {
a = aString;
}
}
在编写实体代码的理念中,方法的内部工作原理对客户端对象是隐藏的。因此,从系统的角度来看,无论是否在循环内或循环外重新声明,都没有区别。由于在循环之外声明它更快,并且不会使代码明显更复杂,因此重用该对象。StringBuilder
即使它要复杂得多,并且您肯定知道对象实例化是瓶颈,也请对其进行注释。
三次运行这个答案:
$ java ScratchPad
1567
$ java ScratchPad
1569
$ java ScratchPad
1570
使用其他答案进行三次运行:
$ java ScratchPad2
1663
2231
$ java ScratchPad2
1656
2233
$ java ScratchPad2
1658
2242
虽然不重要,但设置 的初始缓冲区大小(以防止内存重新分配)将带来较小的性能提升。StringBuilder