2 u011500332 u011500332 于 2013.11.14 23:31 提问

js字符串连接效率问题
    function StringBuffer() {
    this.__strings__ = new Array;    //这里也可以去掉括号
}
StringBuffer.prototype.append = function (str) {
    this.__strings__.push(str);
}
StringBuffer.prototype.toString = function () {
    return this.__strings__.join("");
}
/*
var buffer = new StringBuffer();
buffer.append("hello");
buffer.append("world");
var result = buffer.toString();*/

//用"+"号连接
var d1 = new Date();
var str = "";
for(var i = 0; i < 10000; i++) {
    str += "text";
}
var d2 = new Date();

document.write((d2.getTime() - d1.getTime()));

//用join方法
var oBuffer = new StringBuffer();
var d3 = new Date();
for(var i = 0; i < 10000; i++) {
    oBuffer.append("text");
}
var aResult = oBuffer.toString();
var d4 = new Date();

document.write("<br/>" + (d4.getTime() - d3.getTime()));

居然用“+”连接字符串花的时间比用join的时间短,奇怪了

Csdn user default icon
上传中...
上传图片
插入图片