thomaseng
No Smoking , New Live !

导航

 
//自定义高效的处理字符串拼接的类
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 < 1000000; i++) {
    str += "username";
}
var d2 = new Date();

console.log("Concatenation with plus: " + (d2.getTime() - d1.getTime()) + " milliseconds");

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

console.log("Concatenation with StringBuffer: " + (d2.getTime() - d1.getTime()) + " milliseconds");

  运行结果:

Concatenation with plus: 793 milliseconds Concatenation with StringBuffer: 742 milliseconds
posted on 2013-04-08 01:41  thomaseng  阅读(199)  评论(0编辑  收藏  举报