Traditionally, string connections have been one of the lowest performing operations in JS.
View Source print?
This operation was not optimized by the early browsers. Because the string is immutable, this means that you want to create an intermediate string to store the results of the connection. Frequently creating and destroying strings in the background is abnormally low-performance.
After discovering this, developers use array objects for optimization. Jurong e-Mao Steel
View Source print?
2 |
buffer[i++]= "Hello" ; //通过相应索引值添加元素比push方法快 |
4 |
var text=buffer.join( "" ); |
In earlier browsers, the intermediate strings were not created and destroyed, and in the case of a large number of string connections, this technique has been proven to be much faster than using the addition method.
Now the browser's optimization of strings has changed the way strings are connected. Safari, Opera, Chrome, Firefox, and IE8 all show better performance with addition operators. However, the previous version of IE8 is not optimized, so the array method is still valid. This does not mean that we have to do browser detection when strings are connected. The size and number of strings to consider when deciding how to connect.
When the string is relatively small (less than 20 characters) and the number of connections is also less than 1000, all browsers use the addition operator to easily complete the connection within less than 1 milliseconds. When you increase the number or size of strings, the performance in IE7 decreases significantly. When the size of the string increases, the performance difference between the addition operator and number composition techniques in Firefox is smaller. When the number of strings increases, the performance difference between the addition operators and the composition techniques in Safari becomes smaller. When changing the number or size of strings, the addition operator in Chrome and opera has always been a leading edge.
Therefore, due to inconsistent performance in each browser, the choice of technology depends on the actual situation and the face of the browser.
In most cases, the addition operator is preferred, and if the user primarily uses IE6 or 7, and the string size is large or larger, the array technique is worthwhile.
In general, if you are a semantic string, you should not use an array, such as
View Source print?
1 |
‘Hello, my name is ‘ + name; |
If the string is a "repetition of similar situations," it is recommended to use an array, such as
View Source print?
2 |
for (i = 0; i < length; i++) { |
3 |
array[i] = ‘<li>‘ + list[i] + ‘</li‘ >; |
5 |
document.getElementById( ‘somewhere‘ ).innerHTML = array.join( ‘n‘ ); |
How does JavaScript work with array concatenation strings?