如何实现 SAX 处理程序的 character() 函数以最小化内存使用?
我正在我的 Android 应用程序中实现 java SAX 解析器。
我已经让一切正常工作,但我正在尝试优化一小部分,该部分会占用更多所需的内存。
这是我当前(我知道效率很低)DefaultHandler 的character() 函数。
String currentText = "";
@Override
public void characters(char[] ch, int start, int length)
{
if(currentText.length() > 0)
{
currentText = currentText.concat(new String(ch, start, length));
}else
{
//Takes half as much memory as concating to empty string
currentText = new String(ch, start, length);
}
}
基本上,当 SAX 遇到元素内的文本时,就会调用此函数。值得注意的是,整个文本不能保证立即被解析,因此新字符必须附加到 currentText 中当前的任何文本中(请注意,currentText 在每个元素的末尾设置为“”)。
我只是将这段代码放在一起使其工作,这样我就可以测试解析器的其余部分,但这需要优化。
关于如何实现这一点以使用尽可能少的内存有什么建议吗?
I'm implementing a java SAX parser in my Android app.
I've got everything working, but I'm trying to optimize one little piece that is sucking up a lot more memory that is needed.
This is my current (and quite inefficient I know) implementation of the DefaultHandler's character() function.
String currentText = "";
@Override
public void characters(char[] ch, int start, int length)
{
if(currentText.length() > 0)
{
currentText = currentText.concat(new String(ch, start, length));
}else
{
//Takes half as much memory as concating to empty string
currentText = new String(ch, start, length);
}
}
Basically, this function is called when SAX encounters text inside an element. It's important to note though that the entire text is not guaranteed to be parsed at once, so the new characters must be appended to whatever text is currently in currentText (note that currentText is set to "" at the end of every element).
I just threw this code together to make it work so I could test the rest of my parser, but this needs to be optimized.
Any suggestions on how I can implement this to use as little memory as possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 StringBuilder。
稍后您可以通过调用 currentText.toString() 来获取全文。
更新以模拟修剪:
Use a StringBuilder.
Later on you can get the full text by calling
currentText.toString()
.Update to simulate a trim: