站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题避免创建重复对象

避免创建重复对象

摘要: 避免创建重复对象
<table cellSpacing=0 cellPadding=0 border=0 class="zh114" align="right"> <tr> <td > </td> </tr> </table>
  很简单的一个例子:
  不要使用
  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可以重用以前的对象的。
  而且不要在循环或者多次调用的地方新建一个对象,一定要尽量避免这个

<table width="96%"> <tr> <td background="http:///images/dian.gif" height="3"></td> </tr> </table>

↑返回目录
前一篇: 用私有构造函数强化不可实例化能力
后一篇: 消除对过期对象的引用