在《Java程序与性能优化》一书中
提到过Java的substring方法有内存泄露的问题。其原因是一个String的构造函数引起的。
1
2 3 4 5 |
String
(
int offset,
int count,
char value
[
]
)
{
this. value = value ; this. offset = offset ; this. count = count ; } |
这个构造函数中,对value没有裁剪,因此,一个大的String被减小时,内存得不到释放。
在Java的新版本中,比如JDK8,已经修正了这个问题。在subString中用的构造函数变成了这样:
1
2 3 4 5 6 7 8 9 10 11 12 13 |
public
String
(
char value
[
],
int offset,
int count
)
{
if (offset < 0 ) { throw new StringIndexOutOfBoundsException (offset ) ; } if (count < 0 ) { throw new StringIndexOutOfBoundsException (count ) ; } // Note: offset or count might be near -1>>>1. if (offset > value. length - count ) { throw new StringIndexOutOfBoundsException (offset + count ) ; } this. value = Arrays. copyOfRange (value, offset, offset +count ) ; } |
看到最后一句,value进行的裁剪,内存得到了释放。因此已经不存在这个问题了。大家可以放心用啦~~