String的连接操作之自定义工具类及与+,cancat性能比较

用Javascript面向对象方式,自己编写一个Javascript函数,来进行字符串连接操作.
[color=red]函数代码[/color]如下:

function StringBuffer(){
this._strings = new Array();
}
StringBuffer.prototype.append = function(str){
this._strings.push(str);
};
StringBuffer.prototype.toString = function(){
return this._strings.join("");

};


为了检测一下性能,便与String自带的连接操作(+ 和 concat) 进行了一个性能比较,
[color=red]比较代码[/color]如下:

function StringBuffer(){
this._strings = new Array();
}
StringBuffer.prototype.append = function(str){
this._strings.push(str);
};
StringBuffer.prototype.toString = function(){
return this._strings.join("");
};
function test(){
var d1 = new Date();
var str = "";
for(var i=0;i<10000;i++){
str+="str";
}
var d2 = new Date();
document.write("use + cost time ==" + (d2.getTime() - d1.getTime()) + "<br/>");

var d3 = new Date();
var str2 ="";
for(var i=0;i<10000;i++){
str2=str2.concat("str");
}
var d4 = new Date();
document.write("use concat cost time ==" + (d4.getTime() - d3.getTime()) + "<br/>");

var oBuffer = new StringBuffer();
d5 = new Date();
for(var i = 0 ; i<10000;i++){
oBuffer.append("test");
}
var sResult = oBuffer.toString();
var d6 = new Date();
document.write("use stringBuffer cost time ==" + (d6.getTime()-d5.getTime()) + "<br/>");
}
window.onload=test();


运行,且看结果:
[table]
[color=red]运行结果[/color]|次数|用+| 用concat |用自定义方法|
|1 | use + cost time ==109 |use concat cost time ==141|use stringBuffer cost time ==62
|2 | use + cost time ==250 |use concat cost time ==328|use stringBuffer cost time ==78
|3| use + cost time ==250 |use concat cost time ==266|use stringBuffer cost time ==62

[/table]
[color=red]总结:
用自定义的方法,平均耗时是用+的33%,是用concat的27%,所以三种方法中最耗时的是concat,其次是+.效率最高的应该是自定义的方法
[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值