避免创建重复对象

发表于:2007-06-22来源:作者:点击数: 标签:
很简单的一个例子: 不要使用 String ts=new String(“hello”); 这样会生成多余的对象. 最好使用 String ts=”hello”; //add by chris: 很多文章都建议使用stringbuffer来代替string,为什么会带来 性能 的提高哪? 为了理解深入点,我们看一个例子: Strin

   
  很简单的一个例子:
  不要使用
  String ts=new String(“hello”);
  这样会生成多余的对象.
  最好使用
  String ts=”hello”;
  //add by chris:

  很多文章都建议使用stringbuffer来代替string,为什么会带来性能的提高哪?
  
  为了理解深入点,我们看一个例子:
  String s1 = "Testing String";
  String s2 = "Concatenation Performance";
  String s3 = s1 + " " + s2;
  另外一种方法:
  StringBuffer s = new StringBuffer();
  s.append("Testing String");
  s.append(" ");
  s.append("Concatenation Performance");
  String s3 = s.toString();
     在上面这个例子里面,其实性能是没有提高的,为什么会这样哪?
  这个在这里就不讨论了。有兴趣请研究一下stringbuffer的源代码。
  //end of add
  
  其实在jvm里面,如果你下一次再构造一个值为”hello”的对象string,jvm可以重用以前的对象的。
  而且不要在循环或者多次调用的地方新建一个对象,一定要尽量避免这个

原文转自:http://www.ltesting.net