JavaScript 性能优化之 -- 连接字符串
var str = "hello";
str += "world";
*1:创建存储"hello"的字符串。
*2:创建存储"world"的字符串。
*3:创建存储连接结果的字符串。
*4:把str的当前内容复制到结果中。
*5:把"world"复制到结果中。
*6:更新str,使它指向结果。
1:-----------------正常连接字符串------------------------
var d1 = new Date();
var str = "";
for (var i=0; i < 100000; i++){
str += "test";
}
var d2 = new Date();
document.write("<br/>Concatenation with plus: " + (d2.getTime() - d1.getTime()) + "milliseconds");
2:---------------------用Array和join连接字符串---------------------
var d1 = new Date();
var arr = new Array;
for (var i=0; i < 100000; i++){
arr[i] = "test";
}
var str = arr.join("");
var d2 = new Date();
document.write("<br/>Concatenation with plus: " + (d2.getTime() - d1.getTime()) + "milliseconds");
3:--------------------用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 oBuffer = new StringBuffer();
d1=new Date();
for (var i=0; i < 100000; i++) {
oBuffer.append("text");
}
var sResult = oBuffer.toString();
d2 = new Date();
document.write("<br/>Concatenation with StringBuffer: " + (d2.getTime() - d1.getTime()) + " milliseconds");
=================Google Chrome 28.0.1469.0测试结果==================
1:Concatenation with plus: 125milliseconds
2:Concatenation with plus: 118milliseconds
3:Concatenation with StringBuffer: 95 milliseconds