Home > Article > Web Front-end > [JS Operation Performance Series] Methods of splicing strings and performance comparison
To splice multiple strings together, there are usually three methods, which are often used in practice.
Use the string concatenation operator '+', 'string1' + 'string2' + ...
Use the join function of the array. First write the string into a temporary array, and then call the join method of the array to connect the string elements.
Use the concat function of string.
Method one: Use the string concatenation character '+'
var concat1 = function(str1, str2){ return str1 + str2; };
Method two: Use the join function of the array
var concat2 = function(str1, str2){ var arr = []; arr.push(str1); arr.push(str2); return arr.join(); };
Method three: Use the concat function of the string
var concat3 = function(str1, str2){ return str1.concat(str2); };
Performance summary
I used Benchmark locally to evaluate the above The performance of the two methods was compared. The test environment was Testing in Chrome 46.0.2490 / Mac OS Much higher.
Of course, this is only a test in the chrome 46 environment and does not represent all browser platforms.
There is also a similar performance test in jsPerf https://jsperf.com/concat-vs-...
It will be more efficient to use join in old browsers (ie7-).
In modern browsers, try to use "+" for more efficiency.
Of course, "+" may not necessarily be faster than join in a few modern browsers (for example, Safari 5.0.5, Opera 11.10)
Itself is a string array, and direct join would be better.
Between "+" and concat, of course it is better to use "+", which is convenient, intuitive and efficient.