Some knowledge points of JavaScript String concatenation are worth looking at to improve efficiency. Var str = "hello ";
Str + = "world ";
In fact, the steps behind the scenes are as follows:
(1) create a string that stores "hello.
(2) create a string for storing "world.
(3) create a string that stores the connection results.
(4) copy the current content of str to the result.
(5) Copy "world" to the result.
(6) Update str to point it to the result.
Each time the string connection is completed, steps 2 to 6 are executed, which consumes a lot of resources. If you repeat this process several hundred or even thousands of times, it will cause performance problems. The solution is to use an Array object to store strings, and then use the join () method (the parameter is a Null String) to create the final string. Imagine Replacing the previous code with the following code:
The Code is as follows:
Var str = new Array ();
Str [0] = "hello ";
Str [1] = "world ";
Str. join ("");
In this way, no matter how many strings are introduced in the array, the join operation occurs only when the join () method is called. The procedure is as follows:
(1) create a string for storing the result.
(2) copy each string to a proper position in the result.
The Code is as follows:
Function StringBuilder (){
This. _ string = new Array ();
}
StringBuilder. prototype. Append = function (str ){
This. _ string. push (str );
}
StringBuilder. prototype. toString = function (){
Return this. _ string. join ("");
}
Articles on efficiency improvement:
The fastest way to splice html array strings
StringBuffer class connected to large strings in javascript
For more information, refer to the articles in the past.