android 面试sax内存,android – SAX,StringBuilder和内存泄漏

我有一个奇怪的问题.我正在解析一个包含大文本字段的文档.

在我的角色部分,我正在使用StringBuilder

currentStory.append(ch, start, length);

然后在我的endElement中我将它分配给我对象上的相应字段.

if (name.equals(tagDesc)) {

inDesc = false;

if (currentItem != null ) {

currentItem.setSummaryText(currentStory.toString());

}

currentStory.setLength(0);

}

setSummaryText(String text)方法是:

public void setSummaryText(String text) {

Story = text;

}

而且我的内存耗尽了.

如果我将setSummaryText改为像这样完全奇怪的东西

public void setSummaryText(String text) {

char[] local = text.toString()

Story = new String(local);

}

我很好.我只是无法弄清楚我拿着那个参考? Story是用“”初始化的对象的成员var;

注 – 分配给本地String变量而不是char [] – 也会失败.

解决方法:

Sun javadoc说:

This method can be coded so as to create a new String object without allocating new memory to hold a copy of the character sequence. Instead, the string can share the memory used by the string buffer. Any subsequent operation that alters the content or capacity of the string buffer must then make a copy of the internal buffer at that time. This strategy is effective for reducing the amount of memory allocated by a string concatenation operation when it is implemented using a string buffer.

因为您正在使用带有setLength(0)的StringBuffer,所以它可能会保留对使用toString()创建的所有字符串的引用.

更换:

currentStory.setLength(0);

有:

currentStory = new StringBuffer();

并看看是否解决了它.我认为这不会有任何开销,因为在这两种情况下你都需要创建一个新的char []数组,因为在第一种情况下,数组正由使用toString()创建的String使用.

此外,您应该考虑使用StringBuilder,因为它们比StringBuffer更受欢迎.

标签:android,memory-leaks,sax

来源: https://codeday.me/bug/20190622/1259410.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值