Discuss the performance of js string array concatenation

  • 2020-03-30 04:05:32
  • OfStack

We know that string concatenation is one of the lowest performing operations in js.
Such as:


var text="Hello"; 
text+=" World!"; 

Early browsers did not optimize this operation.
Since strings are immutable, this means creating an intermediate string to store the result of the connection. The frequent creation and destruction of strings in the background leads to poor performance.

Therefore, you can optimize with array objects.
Such as:


var buffer=[],i=0; 
buffer[i++]="Hello";  //Adding elements with corresponding index values is faster than the 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 been shown to be much faster than using addition.
 
Now the browser's optimization of strings has changed the concatenation of strings. Safari, Opera, Chrome, Firefox, and IE8 all show better performance using the addition operator. However, previous versions of IE8 were not optimized, so the array method still works. This does not mean that we need to do browser detection when strings are concatenated. When deciding how to join, consider 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 connect easily in less than a millisecond using the addition operator. When you increase the number or size of strings, the performance in IE7 will decrease significantly. As the string size increases, the performance difference between the addition operator and the number composition technique in Firefox decreases. As the number of strings increases, the performance difference between the addition operator and the number composition trick in Safari decreases. By changing the number or size of strings, the addition operators in Chrome and Opera have always held the lead.

Therefore, due to the inconsistent performance in each browser, the choice of technology depends on the actual situation and the browser facing.

In most cases, the addition operator is preferred; If the user is primarily using IE6 or 7, and the string size is large or large, then the array technique is worth it.
 
In general, Array should not be used if it is a semantic string, such as:
'Hello, my name is' + name;  
 
Array is recommended if the string is a "repeat of the similar case", for example:


var array = []; 
for (i = 0; i < length; i++) { 
array[i] = '<li>' + list[i] + '</li'>; 
} 
document.getElementById('somewhere').innerHTML = array.join('n');

Related articles: