During development, you will also pay attention to using stringbuilder instead of the common String concatenation method. However, most developers may ignore this efficiency issue in Js.
Let's take a performance test and talk about it with facts!
CopyCode The Code is as follows: function xntest (){
VaR d1 = new date ();
VaR STR = "";
For (VAR I = 0; I <10000; I ++ ){
STR + = "stext ";
}
VaR D2 = new date ();
Document. Write ("Time consumed by String concatenation:" + (d2.gettime ()-d1.gettime () + "millisecond ;");
D1 = new date ();
VaR sb = new stringbuilder ();
For (VAR I = 0; I <10000; I ++ ){
SB. append ("stext ");
}
VaR result = sb. tostring ();
D2 = new date ();
Document. Write ("Time consumed in array mode:" + (d2.gettime ()-d1.gettime () + "millisecond ;");
}
//// Use the String concatenation function implemented by array to facilitate C # developers to name stringbuilde for ease of understanding
Function stringbuilder (){
This. _ strings _ = new array;
}
Stringbuilder. Prototype. append = function (STR ){
This. _ strings _. Push (STR );
};
Stringbuilder. Prototype. tostring = function (){
Return this. _ strings _. Join ("");
};
After the xntest () function is executed three times, the result is:
String concatenation time: 735 milliseconds; array time: 62 milliseconds;
String concatenation time: 766 milliseconds; array time: 63 milliseconds;
String concatenation time: 703 milliseconds; array time: 63 milliseconds;
This example is a 10000-time String concatenation performance test. We believe that the results are obvious to all. If you are interested, you can test it on your own.
Therefore, in front-end development, we should also try to avoid large-scale String concatenation operations, and use arrays to reasonably improve code efficiency.