在 javascript 中使用 string buffer 的方法

function StringBuffer(){
    this.content = new Array;
};
StringBuffer.prototype.append = function(str) {
    this.content.push(str);
};
StringBuffer.prototype.toString = function() {
    return this.content.join('');
};

使用範例

var strBuffer = new StringBuffer();
strBuffer.append('aa');
strBuffer.append('bb');
strBuffer.append('cc');
alert(strBuffer.toString());

執行時間測試

var date1 = new Date();
var str = "";
for(i = 0; i<10000; i++){
    str += "nomad";
}
var date2 = new Date();
alert(date2.getTime() - date1.getTime());//getTime()日期的毫秒表示

date1 = new Date();
var strBuffer = new StringBuffer();

for(i = 0; i<10000;i++){
    strBuffer.append("nomad");
}
var result = strBuffer.toString();
date2=new Date();

alert(date2.getTime()-date1.getTime());

結論

只有在 IE 上使用 string buffer 時,效能比較好,在 firefox 反而會慢

應該是因為 firefox 有自行處理字串相接的效能吧,IE 實在是太糟糕了....

所以現階段還是用 string buffer 來處理,畢竟用 IE 的人還是多數~

創作者介紹
創作者 Fear No One 的頭像
choubee

Fear No One

choubee 發表在 痞客邦 留言(0) 人氣( 30 )