1. How to connect strings?
First, let's review the two common methods of string connection:
1.1 Use the String concatenation operator
Common languages (such as Java, C #, and PHP) all have string Concatenation Operators, and Javascript is no exception. Sample Code:
Copy codeThe Code is as follows:
Var str = "";
Str = str + "";
1.2 use Arrays
In common languages, the performance of string connection operations is generally not high. Therefore, in C #, StringBuilder (StringBuffer provided in Java) is used to connect strings. In Javascript, the method of simulating StringBuilder through Array is introduced.
Copy codeThe Code is as follows:
Var str = [];
For (var I = 0; I <100; I ++ ){
Str [I] = "12345 ";
}
Str = str. join ("");
2 Test
The following describes the performance of the two methods by copying strings:
2.1 copy using the String concatenation operator:
Copy 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 codeThe Code is as follows:
Function copyByArray (str, times ){
Var newStr = [];
For (var I = 0; I <times; I ++ ){
NewStr [I] = str;
}
Return newStr. join ("");
}
Str uses a fixed HTML string with a length of 61.
2.3 IE Test
Considering the poor performance of IE, first use a small number of times (6000) to test in IE 6, IE 7, and IE 8. Take the average value after running 10 times. The result is as follows:
Test results in IE browser
Browser |
CopyByOperator |
CopyByArray |
IE 6 |
1780.4 ms |
9.5 ms |
IE 7 |
1754.6 ms |
7.7 ms |
IE 8 |
1.6 ms |
9.4 ms |
IE6, 7 and IE8 test results are far from each other, obviously,IE 8 optimized the string connection operation, which is more efficient than the array COPY method..
2.4 testing in various browsers
Next we will use a relatively large value of times (50000) to test various browsers of the latest version.
Test results of various browsers
Browser |
CopyByOperator |
CopyByArray |
IE 8 |
21.8 ms |
54.7 ms |
Firefox 3.6 |
40.9 ms |
27.9 ms |
Chrome 4 |
4.4 ms |
10.9 ms |
Safari 4.0.5 |
41.6 ms |
34.6 ms |
Opera 10.50 |
33.1 ms |
23 ms |
This result is really unexpected. In IE 8, the string connection operation beat all browsers other than Chrome. You should pay attention to the low performance of IE. In Chrome, the string connection operation is more efficient than the array replication method.
3. Conclusion
The browser's performance is constantly improving. As a front-end engineer, you must adjust the optimization policies of Javascript programs in a timely manner to achieve the best performance.