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?
Use a StringBuilder.
Later on you can get the full text by calling
currentText.toString().Update to simulate a trim: