Even though it is easy to concatenate strings using the + operator, string
operations become very costly in terms of CPU cycle when the strings get bigger and
there are a lot of strings to concatenate.


The better alternative is to create your own StringBuilder JavaScript object that is similar to the StringBuilder object in the .NET Framework. You can define your
StringBuilder object with a buffer array property to store the strings to concatenate. Then add an Append method to add a string to the buffer array. The JavaScript Array object provides a join method that puts all the elements of an array into a string separated by a specified delimiter. ConvertToString method will join all elements of the buffer array into a string.



function StringBuilder()
{
this.buffer = [];
}
StringBuilder.prototype.Append = function(str)
{
this.buffer[this.buffer.length] = str;
};
StringBuilder.prototype.ConvertToString = function()
{
return this.buffer.join('');
};

Instead of the following:



var str = 'This ' + 'is ' + 'a ' + 'test';

You can now use the following:



var sb = new StringBuilder;
sb.Append('This ');
sb.Append('is ');
sb.Append('a ');
sb.Append('test');
var str = sb.ConvertToString();

Our tests indicated that concatenating the string 'test' 50,000 times using the
StringBuilder Append method worked 10 times faster than using the + operator in
Internet Explorer.