We know that in js, string concatenation is one of the lowest performance operations.
For example:
Early browsers did not optimize this operation.
Since strings are immutable, this means creating an intermediate string to store the result of the concatenation. Frequently creating and destroying strings in the background results in extremely low performance.
Therefore, array objects can be utilized for optimization.
For example:
var buffer=[],i=0; buffer[i++]="Hello"; //通过相应索引值添加元素比push方法快 buffer[i++]=" World!"; var text=buffer.join("");
In early browsers, there was no intermediate string creation and destruction. In the case of large number of string concatenations, this technique has been proven to be much faster than using addition.
Nowadays, browser optimization of strings has changed the situation of string concatenation. Safari, Opera, Chrome, Firefox and IE8 all show better performance using the addition operator. However, versions prior to IE8 were not optimized, so the array method still works. This does not mean that we need to do browser detection when string concatenation. Things to consider when deciding how to concatenate are the size and number of strings.
When the string is relatively small (less than 20 characters) and the number of connections is also small (less than 1000), all browsers can easily complete the connection in less than 1 millisecond using the addition operator. Performance drops significantly in IE7 when increasing the number or size of strings. As string sizes increase, the performance difference between addition operators and array composition techniques in Firefox becomes smaller. As the number of strings increases, the performance difference between addition operators and array composition techniques in Safari becomes smaller. The addition operator in Chrome and Opera keeps ahead when changing the number or size of strings.
Therefore, due to inconsistent performance under various browsers, the technology chosen depends on the actual situation and the browser you are facing.
In most cases, the addition operator is preferred; if the user mainly uses IE6 or 7, and the string size is large or there are many, then the array technique is worthwhile.
Generally speaking, if it is a semantic string, Array should not be used, such as:
'Hello, my name is ' name;
If the string is a "repetition of similar situations", it is recommended to use Array, such as:
var array = []; for (i = 0; i < length; i++) { array[i] = '<li>' + list[i] + '</li'>; } document.getElementById('somewhere').innerHTML = array.join('\n');
The performance comparison of js string array connection is introduced here. I hope it will be helpful to everyone.