当前位置: 代码迷 >> Web前端 >> 字符串联接和StringBuffer的对比
  详细解决方案

字符串联接和StringBuffer的对比

热度:118   发布时间:2012-10-24 14:15:58.0
字符串连接和StringBuffer的对比
function StringBuffer () {
  this._strings_ = new Array();
}

StringBuffer.prototype.append = function(str) {
  this._strings_.push(str);
};

StringBuffer.prototype.toString = function() {
  return this._strings_.join("");
};


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

document.write("Concatenation with plus: "
 + (d2.getTime() - d1.getTime()) + " milliseconds");

var buffer = new StringBuffer();
d1 = new Date();
for (var i=0; i < 10000; i++) {
    buffer.append("text");
}
var result = buffer.toString();
d2 = new Date();

document.write("<br />Concatenation with StringBuffer: "
 + (d2.getTime() - d1.getTime()) + " milliseconds");


IE6:
    Concatenation with plus: 79 milliseconds
    Concatenation with StringBuffer: 46 milliseconds
IE7:
    Concatenation with plus: 78 milliseconds
    Concatenation with StringBuffer: 47 milliseconds
IE8:
    Concatenation with plus: 0 milliseconds
    Concatenation with StringBuffer: 15 milliseconds
FF:
    Concatenation with plus: 3 milliseconds
    Concatenation with StringBuffer: 5 milliseconds
Opera:
    Concatenation with plus: 0 milliseconds
    Concatenation with StringBuffer: 16 milliseconds
Chrome:
    Concatenation with plus: 1 milliseconds
    Concatenation with StringBuffer: 3 milliseconds
Safari:
    Concatenation with plus: 1 milliseconds
    Concatenation with StringBuffer: 1 milliseconds
  相关解决方案