Java Language Java Performance Tuning Reducing amount of Strings


Example

In Java, it's too "easy" to create many String instances which are not needed. That and other reasons might cause your program to have lots of Strings that the GC is busy cleaning up.

Some ways you might be creating String instances:

myString += "foo";

Or worse, in a loop or recursion:

for (int i = 0; i < N; i++) {
    myString += "foo" + i;
}

The problem is that each + creates a new String (usually, since new compilers optimize some cases). A possible optimization can be made using StringBuilder or StringBuffer:

StringBuffer sb = new StringBuffer(myString);
for (int i = 0; i < N; i++) {
    sb.append("foo").append(i);
}
myString = sb.toString();

If you build long Strings often (SQLs for example), use a String building API.

Other things to consider:

  • Reduce usage of replace, substring etc.
  • Avoid String.toArray(), especially in frequently accessed code.
  • Log prints which are destined to be filtered (due to log level for example) should not be generated (log level should be checked in advance).
  • Use libraries like this if necessary.
  • StringBuilder is better if the variable is used in a non-shared manner (across threads).