`
yanfaguanli
  • 浏览: 658237 次
文章分类
社区版块
存档分类
最新评论

为什么JDK6中的substring()方法会导致内存泄露?

 
阅读更多

JDK6中subString()的源码

01 //JDK6
02 String(intoffset,intcount,charvalue[]){
03 this.value=value;
04 this.offset=offset;
05 this.count=count;
06 }
07 publicStringsubstring(intbeginIndex,intendIndex){
08 //checkboundary
09 returnnewString(offset+beginIndex,endIndex-beginIndex,value);
10 }

实际上substring并没有去new 一个String对象,substring返回的字符串和之前的字符串是共用的一个字符数组。

只是数组的起点和长度改变了。所以之前的那个被截取的字符串就没有(也不能)被回收。

如果你想要让它能被回收,可以这样substring.

1 x.substring(a,b)+""
2 //or
3 newString(x.substring(a,b))

前者等同于:

1 StringBuildersb=newStringBuilder();
2 sb.append(x.substring(x,y));
3 sb.append("");
4 x=sb.toString();

所以,使用new String(x.substring(a,b))的方式效率更高。


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics