Thursday, September 27, 2007

String And StringBuilder - A Common Mistake

Introduction


Everyone needs the type String in his daily programming. In addition, most of people do a common mistake to choose between String and StringBuilder.

Wrong Approach



String mySentence = null;
mySentence += "I";
mySentence += " ";
mySentence += "am";
mySentence += " ";
mySentence += "writing";
mySentence += " ";
mySentence += "this";
mySentence += " ";
mySentence += "interesting";
mySentence += " ";
mySentence += "article.";


This is not a good approach to deal with String because String is immutable. Therefore, every time when you concatenate the new value a new instance will be made and it will make a great performance loss if concatenation will be done many times.

Right Approach



System.Text.StringBuilder mySentence = new System.Text.StringBuilder();
mySentence.Append("I");
mySentence.Append(" ");
mySentence.Append("am");
mySentence.Append(" ");
mySentence.Append("writing");
mySentence.Append(" ");
mySentence.Append("this");
mySentence.Append(" ");
mySentence.Append("interesting");
mySentence.Append(" ");
mySentence.Append("article.");

The above code will do the same that the wrong approach did but it will lead to the great Performance boost.

Summary


Both approaches are resulting in same manner. You will not see a big difference in one look. However, remember when your code is serving for many requests the above right approach will definitely give you a performance boost.


So remember when you do not want to concatenate then surely use the String and when you have to deal with multiple concatenations then definitely use StringBuilder.

No comments: