Home  >  Article  >  Web Front-end  >  [JS Operation Performance Series] Methods of splicing strings and performance comparison

[JS Operation Performance Series] Methods of splicing strings and performance comparison

高洛峰
高洛峰Original
2016-11-15 14:09:451307browse

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-...

The test results are as follows:


[JS Operation Performance Series] Methods of splicing strings and performance comparisonIt 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn