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”
“chased”
“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”
“chased”
” ”
“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.
Leave a Reply