我有一个奇怪的问题.我正在解析一个包含大文本字段的文档.
在我的角色部分,我正在使用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