Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace using huge heap space

Tags:

java

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]

like image 865
Aka Avatar asked Nov 28 '12 19:11

Aka


People also ask

What happens if heap memory is full in Java?

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.

Can we use string replace?

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.

How do I free up heap space?

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.

Is Java Lang OutOfMemoryError Java heap space?

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.


2 Answers

Use replace() instead of replaceAll(). replaceAll() uses regular expression and you don't need them plus they are overhead.

like image 101
Eng.Fouad Avatar answered Sep 28 '22 00:09

Eng.Fouad


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();
like image 22
Eugene Retunsky Avatar answered Sep 28 '22 01:09

Eugene Retunsky