为什么附加“"以字符串保存内存? [英] Why does appending "" to a String save memory?

查看:9
本文介绍了为什么附加“"以字符串保存内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一个包含大量数据的变量,比如String data.我想通过以下方式使用这个字符串的一小部分:

I used a variable with a lot of data in it, say String data. I wanted to use a small part of this string in the following way:

this.smallpart = data.substring(12,18);

经过几个小时的调试(使用内存可视化器),我发现对象字段 smallpart 记住了来自 data 的所有数据,尽管它只包含子字符串.

After some hours of debugging (with a memory visualizer) I found out that the objects field smallpart remembered all the data from data, although it only contained the substring.

当我把代码改成:

this.smallpart = data.substring(12,18)+""; 

……问题解决了!现在我的应用程序现在使用的内存很少!

..the problem was solved! Now my application uses very little memory now!

这怎么可能?谁能解释一下?我认为 this.smallpart 一直在引用数据,但为什么呢?

How is that possible? Can anyone explain this? I think this.smallpart kept referencing towards data, but why?

更新:那我该如何清除大字符串呢?data = new String(data.substring(0,100)) 会做这件事吗?

UPDATE: How can I clear the big String then? Will data = new String(data.substring(0,100)) do the thing?

推荐答案

执行以下操作:

data.substring(x, y) + ""

创建一个新的(较小的)String 对象,并丢弃对 substring() 创建的 String 的引用,从而启用 this 的垃圾收集.

creates a new (smaller) String object, and throws away the reference to the String created by substring(), thus enabling garbage collection of this.

要意识到的重要一点是,substring()现有 字符串提供了一个窗口 - 或者更确切地说,原始字符串下的字符数组.因此它将消耗与原始字符串相同的内存.这在某些情况下可能是有利的,但如果您想获取子字符串并处理原始字符串(如您所见),则有问题.

The important thing to realise is that substring() gives a window onto an existing String - or rather, the character array underlying the original String. Hence it will consume the same memory as the original String. This can be advantageous in some circumstances, but problematic if you want to get a substring and dispose of the original String (as you've found out).

看看 substring() 方法 JDK String 源代码中的更多信息.

Take a look at the substring() method in the JDK String source for more info.

为了回答您的补充问题,从子字符串构造一个新的字符串将减少您的内存消耗,提供您对原始字符串的任何引用.

To answer your supplementary question, constructing a new String from the substring will reduce your memory consumption, provided you bin any references to the original String.

注意(2013 年 1 月).上述行为已在在 Java 7u6 中改变.不再使用享元模式,substring() 将按预期工作.

NOTE (Jan 2013). The above behaviour has changed in Java 7u6. The flyweight pattern is no longer used and substring() will work as you would expect.

这篇关于为什么附加“"以字符串保存内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆