Is String.concat slower than an Array method for concatenating strings

Strings in JavaScript are immutable. Over the Internet and here is also a stack overflow , I came across an Array approach to concatenate strings:

var a = []; a.push(arg1,arg,2....); console.log(a.join('')); 

I know this approach is better than simple

 console.log(arg1 + arg2 +.....); 

due to omissions of creating intermediate objects, but how it looks better:

 arg1.concat(arg2,arg3.....); 
+4
source share
2 answers

For what it can 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 counted the creation of an array 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 
+3
source

Your question claims that using a .join array is faster than just concatenating strings. Short answer: only in IE is this true.

Other browsers have optimized the + operator, so using arrays or other methods is counterproductive.

+1
source

Source: https://habr.com/ru/post/1307851/


All Articles