Array method solves JS string connection performance problem controversial_javascript skills
- WBOYOriginal
- 2016-05-16 18:12:02960browse
1. Traditionally, string concatenation has always been one of the lowest-performing operations in js.
var text="Hello";
text =" World!";
Early browsers did not optimize this operation.
Since strings are immutable, this means that an intermediate string is created to store the result of the concatenation. Frequently creating and destroying strings in the background results in extremely low performance.
2. After discovering this, developers used array objects for optimization.
var buffer=[],i=0;
buffer[i ]="Hello";//Adding elements through the corresponding index value is faster than the push method
buffer[i ]=" World !";
var text=buffer.join("");
In early browsers, there was no intermediate string creation and destruction. In the case of a large number of string concatenations, this technique has been proven to be much faster. Use the addition method.
3. 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 perform browser detection when string concatenation. Things to consider when deciding how to concatenate are the size and number of strings.
1) When the string is relatively small (2) When increasing the number or size of strings, performance will decrease significantly in IE7.
3) As the string size increases, the performance difference between addition operators and array composition techniques in Firefox becomes smaller.
4) As the number of strings increases, the performance difference between addition operators and array composition techniques in Safari will become smaller.
5) When changing the number or size of strings, the addition operator in Chrome and Opera has always maintained its lead.
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.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn