Javascript三种字符串连接方式及性能比较

第一种:用连接符“+”连接字符串

str="a";
str+="b";

这种方法相对以下两种,最便捷快速。建议100字符以下的连接使用这种连接方式。

第二种:以数组作为中介,使用jion函数进行连接

var arr=new Array();
arr.push(a);
arr.push(b);
var str=arr.join("");

第三种:利用对象属性连接字符串

function stringConnect(){
  this._str_=new Array();
}
stringConnect.prototype.append=function(a){
  this._str_.push(a);
}
stringConnect.prototype.toString=function(){
  return this._str_.join();
}
  var mystr=new stringConnect;
  mystr.append("a");
  var str=mystr.toString(); 

利用下面代码对三种方法性能进行比较,通过更改 c 的值来调整连接字符串的个数:

var str="";
var d1,d2;
var c=5000;//连接字符串的个数
//------------------------测试第三种方法耗费时间-------
 d1=new Date();
function stringConnect(){
  this._str_=new Array();
}
stringConnect.prototype.append=function(a){
  this._str_.push(a);
}
stringConnect.prototype.toString=function(){
  return this._str_.join("");
}
  var mystr=new stringConnect;

  for(var i=0;i<c;i++){
    mystr.append("a");
  }
str=mystr.toString();
 d2=new Date();
 console.log(d2.getTime()-d1.getTime());
//-----------------------------------------------------

//------------------------测试第二种方法耗费时间-------
d1=new Date();
  var arr=new Array();
for(var i=0;i<c;i++){
  arr.push("a");
}
str=arr.join("");
  d2=new Date();
console.log(d2.getTime()-d1.getTime());
//-------------------------------------------------------
//------------------------测试第一种方法耗费时间-------
d1=new Date();for(var i=0;i<c;i++){
  str+="a";
}
d2=new Date();
console.log(d2.getTime()-d1.getTime());
//-------------------------------------------------------

我调整 c 分别等于5000、50000、500000、5000000,每个数值分别测了10次,最后结果如下:

c=5000
                                                                             平均耗时(单位毫秒)

第三种   3   2   2   3   1   2  2  1   1   1                              1.8
第二种   1   3   0   3   1   3  4  1   4   2                              2.2
第一种   0   0   0   0   0   1  1  1   1   1                              0.5

c=50000

第三种   22  12     9   14    12   13   13   13   10   17          13.5
第二种   8    13   12     8    11   11     8     9     8    9          9.7
第一种   7    12     5    11   10   10   10    13   16  12          10.6

c=500000

第三种 104 70 74 69 76 77 69 102 73 73                            78.7
第二种 78 100 99 99 100 98 96 71 94 97                             93.2
第一种 90 87 83 85 85 83 84 83 88 86                                 85.4

c=5000000

第三种 651 871 465 444 1012 436 787 449 432 444             599.1
第二种 568 842 593 747 417 747 719 549 573 563               631.8
第一种 516 279 616 161 466 416 201 495 510 515               417.5

统计5000000的时候在地址栏加入了随机参数,应该是避免了缓存的影响的。从结果来看,第一种方法并不比另2种方法消耗多,甚至还更有优势,这点和手册上的说明明显不一致。

测试系统:win 7旗舰

浏览器:chrome 52.0.2739.0 m

总结

以上所述是小编给大家介绍的Javascript三种字符串连接方式及性能比较,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!