用StringBuffer优化字符串性能
[作者]:菩提树下的杨过 [来源]:互联网 [收录时间]:2007-9-16 12:43:41

使用操作符+=或+来串连字符串是一种简便的方法,但在对于性能有要求的场合中并不适用.实例证明使用StringBuffer而不是使用操作符+=或+来串连字符串可以提升程序的性能.

参见如下的代码:

public class StringBuff{
 public static void main(String arg[]){
  final int N = 10000;
  
  //用操作符串联两个字符串
  long startTime = System.currentTimeMillis();
  String s1 = "a";
  for(int i=1;i<N;i++){
   s1 += "*";
  }
  long endTime = System.currentTimeMillis();
  System.out.println("用操作用操作符串联两个字符串: " + (endTime-startTime) + "ms");
  
  //通过StringBuffer串连两个字符串
  startTime = System.currentTimeMillis();
  StringBuffer sb = new StringBuffer();
  for(int i=1;i<N;i++){
   sb.append("*");
  }
  String s2 = sb.toString();
  endTime = System.currentTimeMillis();
  System.out.println("用StringBuffer串联两个字符串: " + (endTime-startTime) + "ms");
  
 }
}

运行结果:

用操作用操作符串联两个字符串: 1187ms
用StringBuffer串联两个字符串: 16ms

运行环境:

AMD Duron 1.6GHz,256M DDR,Windows XP SP2,J2SE 5.0 update 1

运行结果显示,使用StringBuffer的append()方法串连字复串相较于使用字符串操作符有教大的性能差异.所以在对性能有要求的情况下,应该使用StringBuffer来实现串联字符串.