CopyCode The Code is as follows: var STR = "hello ";
STR + = "world ";
Background work:
1) create a string that stores "hello" and point STR to it.
2) create a string for storing "world.
3) create a string for storing the result.
4) copy the current content in STR to the result string.
5) Copy world to the result string.
6) Update STR to point STR to the result string.
Repeat each concatenated string. 2 )~ 6) if you repeat hundreds of times, it will consume a lot of resources and affect performance.
Solution:
Use the array object to store strings, and then use the join () method to output the results.
This is similar to the stringbuffer class in Java.Copy codeThe Code is 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: concatenate a string using "+ ="Copy codeThe Code is 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: Use stringbufferCopy codeThe Code is 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 the results of Multiple tests, stringbuffer can save more than 50% of the time.