var str="hello";
str ="world";
In fact, the steps performed by this code behind the scenes are as follows:
(1) Create a string to store "hello".
(2) Create a string to store "world".
(3) Create a string to store the connection result.
(4) Copy the current content of str to the result.
(5) Copy "world" into the result.
(6) Update str so that it points to the result.
Steps 2 to 6 will be executed every time string concatenation is completed, making this operation very resource-consuming. If this process is repeated hundreds, or even thousands, of times, it can cause performance problems. The solution is to use an Array object to store the string, and then use the join() method (the parameter is an empty string) to create the final string. Imagine replacing the previous code with the following code:
var str =new Array();
str[0]="hello";
str[1]="world";
str.join("");
This way, no matter how many strings are introduced into the array, it won't be a problem because the join operation only occurs when the join() method is called. At this point, the steps are as follows:
(1) Create a string to store the result.
(2) Copy each string to the appropriate location in the result.
function StringBuilder(){
this._string= new Array();
}
StringBuilder.prototype.Append=function(str){
this._string.push(str);
}
StringBuilder.prototype.toString=function( ){
return this._string.join("");
}
Related articles to improve efficiency:
The fastest way to splice html array strings StringBuffer class for connecting large strings in JavaScript For more information, please refer to previous articles of Script House.
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