There are many ways to join multiple strings together in JavaScript. The simplest one is by using the '+' operator. This is what almost everyone learns when they start programming in JavaScript:
'mac' + ' and ' + 'cheese' The problem with this method is that some browser does not implement the '+' operator efficiently (
in the case of IE, by using intermediate buffer) which makes the concatenation of many strings virtually impractical. The performance degradation is obvious when joining more than 10,000 strings.
The better way is to use array as buffer by storing each separate string as array elements and then use join() method on the array to get the resulting string. Some implementations of this method uses
Array.length or
Array.push to keep track of the next location to store the string:
var sb = [];sb[sb.length] = 'mac';sb[sb.length] = ' and ';sb[sb.length] = 'cheese';
sb.join(''); or
var sb = [];sb.push('mac');sb.push(' and ');sb.push('cheese');
sb.join(''); Both of these methods offer a magnitude of performance improverment over '+' operator, especially in IE. To go a little further, we can use a local variable to keep track of the last position. I get another 20 - 25% improvement over the above method in IE.
Update: IE8 now implements a faster string concatenation.var sb = [], // Use this array as a string bufferl = 0; // To keep track of the array lengthsb[l++] = 'mac';sb[l++] = ' and ';sb[l++] = 'cheese';sb.join('');This method reduce the number of memory operations, in this case,
Array.length or
Array.push which, according to the spec, JavaScript runtime must traverse the prototype chain to look for
length or
push property, then executing a function call (in the case of
push) as oppose to evaluation of local variable and one increment operation per string. Furthermore, your code will also be smaller.