android - SAX、StringBuilder 和内存泄漏

标签 android memory-leaks sax

我有一个奇怪的问题。我正在解析带有大文本字段的文档。 在我的角色部分,我使用的是 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 是这个对象的成员变量,用“”初始化; 注意 - 分配给本地 String 变量而不是 char[] - 也会失败。

最佳答案

我认为这可能与 StringBuffer toString() 的性能优化有关方法。

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.

因为您将 StringBuffersetLength(0) 一起使用,所以它可能会保留对使用 toString( )

替换:

currentStory.setLength(0);

与:

currentStory = new StringBuffer();

看看是否能解决问题。我认为这不会有更多的开销,因为在这两种情况下您都需要创建一个新的 char[] 数组,因为在第一种情况下该数组被 使用使用 toString() 创建的字符串

此外,您应该考虑使用 StringBuilder因为它们优于 StringBuffer

关于android - SAX、StringBuilder 和内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2016054/

相关文章:

Android:如何使用 SensorManager.getAltitude(float p0, float p)?

memory-leaks - 最小 D 程序中的内存泄漏?

java - 将 Java DOM 文档序列化为 XML : Add CData Elements

android - 如果要向Android Debounce添加条件,该怎么办?

android - 字符出现在 TextView 的屏幕外!

c - Valgrind — 堆统计数据很奇怪 : memory leak?

填充列表时 Python 内存泄漏 - 如何修复?

java - 解析 xml 的更好方法

python - 如何使用 Python 对大 XML 文件执行查询?

java - Android通过DDMS访问设备中备份的文件