The importance of StringBuffer

I know I’ve said it a million times, its not really blog-ish content, and its documented ad nauseum all over the place, but you really need to use a StringBuffer when building large String objects from smaller String constituents. I have run across some issue with it lately so I want to add my contribution to the cause for anyone who may read this.

Take the following:

String dog = "The dog";
String cat = "the cat";
String action = "chased";

String sentence = dog + action + cat;

This code produces “The dogchasedthe cat”;

Its ugly, but I want to illustrate the big issue here.

The above code has produced 5 Strings:
“The dog”
“the cat”
“The dogchased”
“The dogchasedthe cat”

Each of these is an object in the JVM taking up memory. And this is a very simple scenario. If we do some simple improvements that would be necessary to make this code usable look what happens:

String dog = "The dog";
String cat = "the cat";
String action = "chased";
String space = " ";

String sentence = dog + space + action + space +cat;

This code produces “The dog chased the cat” and it produced 8 Strings:
“The dog”
“the cat”
” ”
“The dog ”
“The dog chased”
“The dog chased ”
“The dog chased the cat”

Imagine if you are forumlating complex SQL or XML using inputs from a web form. You could create hundreds of strings per request. Its just a bad practice. Make sure you use StringBuffer.

Posted in code, java

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Blog Stats
  • 8,108 hits
%d bloggers like this: