function StringBuffer () {
this._strings_ = new Array();
}
StringBuffer.prototype.append = function(str) {
this._strings_.push(str);
};
StringBuffer.prototype.toString = function() {
return this._strings_.join("");
};
/***
实际上,这段代码在幕后执行的步骤如下:
创建存储 " " 的字符串。
创建存储 "text" 的字符串。
创建存储连接结果的字符串。
把 str 的当前内容复制到结果中。
把 "text" 复制到结果中。
更新 str,使它指向结果。
***/
var d1 = new Date();
var str = "";
for (var i=0; i < 500000; 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 < 500000; i++) {
buffer.append("text");
}
var result = buffer.toString();
d2 = new Date();
document.write("<br />Concatenation with StringBuffer: "
+ (d2.getTime() - d1.getTime()) + " milliseconds");
/****
Concatenation with plus: 93 milliseconds
Concatenation with StringBuffer: 26 milliseconds
***/