Java String.split 内存泄漏? [英] Java String.split memory leak?
问题描述
我发现使用 String.substring
会导致与 String.split
相关的内存问题.
I found that using String.substring
is known for memory issues related to String.split
.
使用 String.split
是否存在内存泄漏?
Is there a memory leak in using String.split
?
如果是,它的解决方法是什么?
If yes what is the work-around for it?
以下链接显示了 Java 中子字符串的正确用法.
Following link show correct usage of substring in Java.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4513622
另一篇讨论子字符串中可能的 MLK 的博客.
One more blog which talk about possible MLK in substring.
http://nflath.com/2009/07/the-dangers-of-stringsubstring/
推荐答案
更新: 行为在 1.7.0_06 中发生了变化:请参阅这篇文章:Java 1.7.0_06 中对字符串内部表示的更改,位于 java-performance.info.
Update: Behavior has changed in 1.7.0_06: See this article: Changes to String internal representation made in Java 1.7.0_06 at java-performance.info.
正如 @finnw 所指出的,使用 String 时确实存在某种内存泄漏.子串
.原因是 String.substring
只返回给定字符串的一部分的视图,即,底层字符串仍然保留在内存中.
As pointed out by @finnw there is indeed kind of a memory leak lurking around when using String.substring
. The reason is that String.substring
only returns a view of a portion of the given string, i.e., the underlying string is still kept in memory.
要强制创建与源无关的新字符串,您必须使用 new
关键字.即,你必须做例如
To force the creation of a new string, unrelated to the source, you'll have to use the new
keyword. I.e., you'll have to do for instance
String[] parts = orig.split(";");
//String mySubstring = parts[i]; // keeps orig from being GC'd
String mySubstring = new String(parts[i]); // creates a new string.
或者,也许更直接
String mySubstring = new String(orig.split(";")[i]);
<小时>
我必须说这种行为对我来说似乎不必要".它应该可以使用弱引用或其他一些技术来解决.(特别是考虑到 String
已经是一个特殊的类,Java 语言规范的一部分.)
I must say that this behavior seems "unnecessary" to me. It should be solvable using weak references or some other technique. (Especially considering that String
is already a special class, part of the Java language specification.)
这篇关于Java String.split 内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!