用Javascript面向对象方式,自己编写一个Javascript函数,来进行字符串连接操作.
函数代码如下:
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) 进行了一个性能比较,
比较代码如下:
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();
运行,且看结果:
| 次数 | 用+ | 用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 |
总结:
用自定义的方法,平均耗时是用+的33%,是用concat的27%,所以三种方法中最耗时的是concat,其次是+.效率最高的应该是自定义的方法