java split 内存,Java String.split内存泄漏?

这篇博客讨论了Java中使用String.substring可能导致的内存问题,指出它实际上返回的是源字符串的一个视图,导致原始字符串无法被垃圾回收。文章提到了从1.7.0_06版本开始的行为变化,并提供了使用new关键字创建独立字符串以避免内存泄漏的建议。作者认为这种行为有些‘不必要的’,并提出可能通过弱引用等技术来解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I found that using String.substring is known for memory issues related to String.split.

Is there a memory leak in using String.split?

If yes what is the work-around for it?

Following link show correct usage of substring in Java.

One more blog which talk about possible MLK in substring.

解决方案

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.

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.

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.

or, perhaps more direct

String mySubstring = new String(orig.split(";")[i]);

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.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值