Is String.concat slower than Array approach to join strings

javascript

Solution

For what it may count, I tried the following test:

var stringA = 'someStringA';
var stringB = 'someStringB';
var stringC = 'someStringC';

var arr = [];
arr.push(stringA);
arr.push(stringB);
arr.push(stringC);

// Testing the concat method
i = 0;
console.time('10k concat');
while (i < 10000) {
    stringA.concat(stringB, stringC);
    i++;
}
console.timeEnd('10k concat');

// Testing the join method
i = 0;
console.time('10k join');
while (i < 10000) {
    arr.join(''); 
    i++;
}
console.timeEnd('10k join');

Results in Firefox 3.6.3 on Mac OS X 10.6.2:

10k concat: 20ms
10k join: 15ms

10k concat: 20ms
10k join: 16ms

10k concat: 19ms
10k join: 15ms

Results in Chrome 5.0 on Mac OS X 10.6.2:

10k concat: 22ms
10k join: 14ms

10k concat: 20ms
10k join: 16ms

10k concat: 20ms
10k join: 16ms

UPDATE:

If we were to count the array creation in the `join('')` test, we would see a different story. Testing:

var stringA = 'someStringA';
var stringB = 'someStringB';
var stringC = 'someStringC';

// Testing the concat method
i = 0;
console.time('10k concat');
while (i < 10000) {
    stringA.concat(stringB, stringC);
    i++;
}
console.timeEnd('10k concat');

// Testing the join method
i = 0;
console.time('10k join');
while (i < 10000) {
    var arr = [];
    arr.push(stringA);
    arr.push(stringB);
    arr.push(stringC);
    arr.join(''); 
    i++;
}
console.timeEnd('10k join');

Results in Firefox 3.6.3 on Mac OS X 10.6.2:

10k concat: 20ms
10k join: 40ms

10k concat: 21ms
10k join: 40ms

10k concat: 20ms
10k join: 42ms

Results in Chrome 5.0 on Mac OS X 10.6.2:

10k concat: 20ms
10k join: 55ms

10k concat: 22ms
10k join: 60ms

10k concat: 19ms
10k join: 60ms

Problem

Strings in JavaScript are immutable. Across the web and here on Stack Overflow as well, I came across the Array approach to concatenate strings: ``` var a = []; a.push(arg1,arg,2....); console.log(a.join('')); ``` I know that this approach is better than the simple ``` console.log(arg1 + arg2 +.....); ``` for reasons of skipping creating intermediate objects but how does it fair better against : ``` arg1.concat(arg2,arg3.....); ```

Original source

Related problems