We know that in js, string concatenation is one of the lowest performing operations.
For example:
The code copy is as follows:
var text="Hello";
text+=" World!";
Early browsers did not optimize this operation.
Since strings are immutable, this means creating intermediate strings to store the results of the connection. Frequently creating and destroying strings in the background, the performance of constraining is extremely poor.
Therefore, optimization can be performed using array objects.
For example:
var buffer=[],i=0; buffer[i++]="Hello"; //Adding elements through the corresponding index value is faster than push method buffer[i++]="World!"; var text=buffer.join("");In early browsers, intermediate strings were not created and destroyed, and in the case of a large number of string concatenations, this technique has proved far faster than using addition methods.
Nowadays, browser optimization of strings has changed the situation of string connection. Safari, Opera, Chrome, Firefox, and IE8 all show better performance when using addition operators. However, versions before IE8 have not been optimized, so the array method is still valid. This does not mean that when strings are connected, we need to perform browser detection. What you need to consider when deciding how to connect is the size and number of strings.
When the string is relatively small (less than 20 characters) and the number of connections is small (less than 1000), all browsers can easily complete connections in less than 1 millisecond using the addition operator. When increasing the number or size of strings, the performance in IE7 will be significantly reduced. When the string size increases, the performance difference between addition operators and component techniques in Firefox will become smaller. As the number of strings increases, the performance differences between addition operators and component techniques in Safari will become smaller. Additive operators in Chrome and Opera have always maintained a lead when changing the number or size of strings.
Therefore, due to the inconsistent performance of each browser, the technology selection depends on the actual situation and the browser you are facing.
In most cases, addition operators are preferred; array technology is worth it if users mainly use IE6 or 7 and have large string sizes or large numbers.
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 "repeat 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');That's all for the performance comparison of js string array connections, I hope it will be helpful to everyone.