If you are dynamically generating strings in your Java program, one of the best things you can do for your program is to build your string using a StringBuilder
or StringBuffer
, as opposed to using a regular old String
.
The reason for this? In Java, strings are immutable, and every time you concatenate a string that the program hasn’t seen before, a new string object is created and stored in the heap. This means the whole process involves a lot of reading from and writing to the memory. The StringBuilder
and StringBuffer
in Java are objects that are designed to do string concatenation in a more efficient manner, but how much more?
We’ve got a simple Java program here that you can run from your browser so you can see it for yourself.
Continue reading →