Reducing amount of Strings

suggest change

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++) {
myString = sb.toString();

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

Other things to consider:

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents