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

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

问题描述

我使用了包含大量数据的变量,例如字符串数据
我想通过以下方式使用此字符串的一小部分:

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!

这怎么可能?有谁能解释一下?我认为这个小部分一直在引用数据,但为什么呢?

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的引用,从而实现对此的垃圾收集。

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

要认识到的重要一点是 substring()现有 String - 或者更确切地说,是原始String下面的字符数组。因此它将消耗与原始String相同的内存。这在某些情况下可能是有利的,但如果你想得到一个子串并处理原始字符串(如你所知),则会有问题。

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

看一看在子串JDK字符串源代码中的()方法以获取更多信息。

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 。不再使用flyweight模式, 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天全站免登陆