关于字符串

  消除字符串连接,在程序中优先考虑使用StringBuffer或者StringBuilder代替String。一个字符串相当于一个匿名的String对象,如果在程序中拼接两个字符串那么会在内存中定义三个字符串空间。而StringBuffer或者StringBuilder不会这么做,而是在原来已有的StringBuffer或者StringBuilder对象中进行修改。测试代码如下

public class Test3{
 public static void main (String [] args)
 {
  long time1Before=System.nanoTime();
  String str="";
  for(int i=0;i<10000;i++){
   str+=i;
  }
  long time1After=System.nanoTime();
  System.out.println("use String --->  "+(time1After-time1Before));

  long time2Before=System.nanoTime();
  StringBuilder sbuilder=new StringBuilder();
  for(int i=0;i<10000;i++){
   sbuilder.append(i);
  }
  long time2After=System.nanoTime();
  System.out.println("use StringBuilder--->  "+(time2After-time2Before));

  long time3Before=System.nanoTime();
  StringBuffer stringBuffer=new StringBuffer();
  for(int i=0;i<10000;i++){
   stringBuffer.append(i);
  }
  long time3After=System.nanoTime();
  System.out.println("use StringBuffer--->  "+(time3After-time3Before));
 }
}

  需要说明的是在StringBuffer和StringBuilder之间如果需要考虑选其一的话原则很简单,前者是线程安全的后者是线程不安全的,换句话说后者比前者更快。综上所述如果单单从性能上考虑的话从高到低依次是:StringBuilder --> StringBuffer --> String。

  循环和字符串是程序中容易提升代码效率的地方,因为很多人在写程序的时候为了图一时方便将效率抛在脑后,当要处理的数据不大的时候无所谓,一旦程序要处理的数据增大那么性能的瓶颈也出现了。所以像文章开头所说的,要在写程序的时候要考虑十万百万的数量级,不要等到性能瓶颈出现再去解决,因为代码重构或者说后期的优化成本要远远高于前期的开发成本,相信看过别人无注释而又冗长代码的童鞋深有体会(窃笑~~)。