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!
Copy codeThe 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.