Copy Code code as follows:
var str = "Hello";
str = "World";
Work in the background:
1 creates a string that stores "Hello" and causes Str to point to it.
2 Create a string that stores "world".
3 Create a string that stores the results.
4 Copy the current content in Str to the result string.
5 Copy the world into the result string.
6 Update str so that STR points to the result string.
Each stitch string repeats 2 ~6), and if repeated hundreds of times it consumes resources and affects performance.
Workaround:
Use the Array object to store the string, and then use the join () method to output the result.
Modeled after the StringBuffer class in Java.
Copy Code code as follows:
function StringBuffer () {
This._strings = new Array;
}
StringBuffer.prototype.append = function (str) {
This._strings.push (str);
}
StringBuffer.prototype.toString = function () {
Return This._strings.join ("");
}
Test performance:
Code 1: Concatenation of strings with "+ ="
Copy Code code as follows:
var d = new Date ();
var str = "";
for (Var i=0;i<10000;i++) {
STR + + "TEST";
}
var d2 = new Date ();
Document.writeln (D2.gettime ()-d.gettime ());
Code 2: Using StringBuffer
Copy Code code as follows:
var d = new Date ();
var str = new StringBuffer ();
for (Var i=0;i<10000;i++) {
Str.append ("test");
}
var res = str.tostring ();
var d2 = new Date ();
Document.writeln (D2.gettime ()-d.gettime ());
From multiple test results, the use of StringBuffer can save more than 50% of the time.