SoFunction
Updated on 2025-03-01

On the performance of string connection under Javascript

1 How to conduct string concatenation?

First, let's review two common methods of string concatenation:
1.1 Using string concatenation operators

Commonly used languages ​​(such as Java, C#, PHP, etc.) have string concatenation operators, and Javascript is no exception. Code examples:

Copy the codeThe code is as follows:

var str = "";
str = str + "a";

1.2 Using Arrays

In common languages, the performance of string concatenation operations is generally not high. For this reason, StringBuilder (StringBuffer is provided in Java) is specially provided in C# for concatenating strings. And in Javascript, a solution to simulate StringBuilder through Array appears.
Copy the codeThe code is as follows:

var str = [];
for (var i = 0; i < 100; i++) {
str[i] = "12345";
}
str = ("");

2 Test

The following is a process of copying strings to test the performance of the two methods:
2.1 Copy through string concatenation operator:
Copy the codeThe code is as follows:

function copyByOperator(str, times) {
var newStr = "";
for (var i = 0; i < times; i++) {
newStr += str;
}
return newStr;
}

2.2 Copy through arrays:
Copy the codeThe code is as follows:

function copyByArray(str, times) {
var newStr = [];
for (var i = 0; i < times; i++) {
newStr[i] = str;
}
return ("");
}

str takes a fixed HTML string with a length of 61.
2.3 Testing under IE

Considering that IE's performance is relatively poor, we first use a small times value (6000) to test under IE 6, IE 7 and IE 8. After running 10 times, the average value is taken, and the result is as follows:
Test results under IE browser
Browser copyByOperator copyByArray
IE 6 1780.4ms 9.5ms
IE 7 1754.6ms 7.7ms
IE 8 1.6ms 9.4ms

The test results of IE6, 7 and IE8 are far apart, and it is obvious thatIE 8 optimizes string concatenation operations, and its efficiency is already higher than array copying method

2.4 Tests under various browsers

Next, we will use a relatively large times value (50000) to test the latest versions of various browsers.

Test results for various browsers
Browser copyByOperator copyByArray
IE 8 21.8ms 54.7ms
Firefox 3.6 40.9ms 27.9ms
Chrome 4 4.4ms 10.9ms
Safari 4.0.5 41.6ms 34.6ms
Opera 10.50 33.1ms 23ms

This result is really unexpected. The string connection operation under IE 8 actually defeats browsers other than Chrome. Those who always say that IE performance is low should be paid attention to. In Chrome, string concatenation operations are also more efficient than array copying.

3 Summary

The performance of the browser is constantly improving. As a front-end engineer, you must also adjust the optimization strategy of Javascript programs in a timely manner to obtain the best performance.