During development, everyone will also pay attention to using StringBuilder as much as possible instead of ordinary string splicing methods. But perhaps most developers have overlooked that this efficiency issue also needs to be paid attention to in js.
Let’s conduct a performance test and let the facts speak for themselves!
function xntest(){
var d1=new Date();
var str="";
for(var i=0;i<10000;i ){
str ="stext";
}
var d2=new Date();
document.write("String concatenation method takes time:" (d2.getTime()- d1.getTime()) "Milliseconds;");
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 consuming in array mode:" (d2.getTime()- d1.getTime()) "Milliseconds;");
}
/////The string splicing function implemented using Array is specially named StringBuilde for the convenience of c# developers to make it easier to understand
function StringBuilder(){
this._strings_=new Array;
}
StringBuilder.prototype.append=function(str){
this._strings_.push(str);
};
StringBuilder.prototype.toString=function(){
return this._strings_.join("");
};
The result after executing the xntest() function three times is:
String splicing method takes 735 seconds Milliseconds; array method takes 62 milliseconds;
String concatenation method takes 766 milliseconds; array method takes 63 milliseconds;
String concatenation method takes 703 milliseconds; array method takes 63 milliseconds Milliseconds;
This example is a performance test of splicing strings 10,000 times. I believe the results are obvious to all. Interested friends can test it themselves.
Therefore, in front-end development, we should also try to avoid large-scale string splicing operations, and should use array methods to reasonably improve code efficiency.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn