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++) {
    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:

Feedback about page:

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


Performance Tuning:
* Reducing amount of Strings

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
91 Performance Tuning
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap