java substring内存泄露的解决
来源:互联网 发布:ios 存储数组 编辑:程序博客网 时间:2024/05/20 10:54
在《Java程序与性能优化》一书中
提到过Java的substring方法有内存泄露的问题。其原因是一个String的构造函数引起的。
1
2
3
4
5
2
3
4
5
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
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
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);
}
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进行的裁剪,内存得到了释放。因此已经不存在这个问题了。大家可以放心用啦~~
0 0
- java substring内存泄露的解决
- substring内存泄露原因及解决
- Java中的substring真的会引起内存泄露么
- Java中的substring真的会引起内存泄露么?
- Java中的substring真的会引起内存泄露么?
- Java中的substring真的会引起内存泄露么?
- Java中的substring真的会引起内存泄露么?
- Java中的substring真的会引起内存泄露么?
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- Java内存泄露的理解与解决
- 函数包装器,函数私有类处理
- C语言 select函数使用
- java 8 使用Lambdas, Paths and Files
- 函数模板,函数模板重载,可变参数模板,函数模板覆盖,通过引用交换数据
- 浅谈HibernateTemplate类的使用
- java substring内存泄露的解决
- chrome 新建标签时的缺省页如何DIY?
- 的副本刚大范甘迪刚刚容易容易和激光焊接
- 慎用自动装箱
- 依赖链接器最小化编译时间(Abusing the Linker to Minimize Compilation Time)
- windows / linux中【FTP命令】的使用
- Android 数据存储 之 SQLite数据库详解
- 高度平衡树 -- AVL 树
- C++中的数组array和vector,lambda表达式,C字符串加操作,C++中新类型数组(数组缓存),多元数组,new缓冲