Code Comments

Code Comments

Tips and short tutorials on various programming technologies

Code Comments RSS Feed
 
 
 
 

In Java, Use StringBuilder When Constructing Large Strings

This bit of advice is not new to me nor to the software development community. But recently I had one of those experiences where I put together a quick solution (to keep my code as simple as possible), and later I ran into a performance problem. And it was because I was violating this principle.

I am generating a very large string (based on values that are read from a text file). I had instantiated a string and was appending to the end of it, like so:

String output = "";
for (String line : fileReader)
  output += line;

And it was going v….e….r….y…s….l….o….w. After figuring out where the slowness was occurring, I used the StringBuilder instead. And it started going fast! Here’s the general idea of the change to the code.

StringBuilder output = new StringBuilder();
for (String line : fileReader)
  output.append(line);

The reason the latter is so much faster is that it only has to create one object in memory: the StringBuilder object. If you just use a String, it has to recreate a new String object in memory each time you append to it.

Just something to keep in mind.

Leave a Reply