I am doing a xml parsing and doing some string replaceAll
which is using a huge amount of memory space as shown in the below image.
Code goes like:
private final String getText() {
// special handling for apostrophe encoding
// site will expect both ' , ' and %27.
// change %27 or 'or ' to '
return _text.toString().trim().replaceAll("'", "'")
.replaceAll("'", "'").replaceAll("%27", "'");
}
The getText()
method is frequently call from endElement()
method of SAXParser.
Can anyone suggest how do change this functionality which will use lesser heap space
![trace][1]
Java objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
The replace() method returns a copy of the string where the old substring is replaced with the new substring. The original string is unchanged. If the old substring is not found, it returns the copy of the original string.
Once an object is not referenced by any other object, it can be cleared out of the heap, in order for the JVM to reclaim and reuse that space. The execution thread that is responsible to clear the heap space is the Garbage Collector.
A java. lang. OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java.
Use replace()
instead of replaceAll()
. replaceAll()
uses regular expression and you don't need them plus they are overhead.
Using regular expressions for simple string replacement like this is too expensive. I would simply build a StringBuilder instance like this:
StringBuilder sb = new StringBuilder();
while (not end of _text) {
find next '&'
if the next substring is in (' ') etc.
append the prev portion of _text to sb
append replacement char
set the beginning of the chunk to the next char
}
return sb.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With