虽然在 java 中我们不用关心内存的释放, 垃圾回收机制帮助我们回收不需要的对象,但实际上不正当的操作也会产生内存问题:如,内存溢出、内存泄漏
内存溢出:out of memory:简单通俗理解就是内存不够用了 。
内存泄漏:leak of memory:一个对象分配内存之后,在使用结束时未及时释放,导致一直占用内存,没有及时清理,使实际可用内存减少,就好像内存泄漏了一样。
比如在 jdk6 中不恰当使用 substring() 方法容易引发内存泄漏,JDK7 就无需考虑
jdk6 的 substring 源码:使用的是和父字符串同一个 char 数组 value
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); jdk7 的 substring 源码:可以看出最后创建了一个新的 char 数组
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex> value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
来源: http://www.bubuko.com/infodetail-2433225.html