java substring问题

substring一般用于我们截取字符串操作,但是在java6的时候这个截取字符串操作会导致一个内存泄漏的问题。
看下java6中的源码,不难发现substring操作仅是在原字符串数组上操作,仅修改了截取位置。因为我们如果在某些情况下我们截取一个超大的字符串的某一截的时候,事实上这个超大字符串仍然占用着内存空间没有被释放,当这种占用过多或者其他原因内存不够的时候就会出现内存泄漏的问题。

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}

String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}

既然发现了这个问题,java7中也很快的修复了,但是修复方式是直接生成一个新的对象,这与java6不同,但是实际上称不上是一个优秀的改动,实际上只是为了避免问题然用一个不怎么理想的方式去规避了罢了。因为这种实现性能会下降,共享字符串数组的方式更加的快速。

猜你喜欢

转载自blog.csdn.net/runlion_123/article/details/105952987