字符串拼接方式(待商榷)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>字符串拼接方式</title>
<script type="text/javascript">
//方法一:普通拼接
var beginDate = new Date();
var str = "";
for (var i = 0; i < 100000; i++) {
str += "text";
}
var endDate = new Date();
document.write("方法一:普通拼接,耗时:" + (endDate.getTime() - beginDate.getTime()) + "毫秒<br/>");
//方法二:数组拼接
function StringBuilder() {
this.__strings__ = new Array;
}
StringBuilder.prototype.append = function (str) {
this.__strings__.push(str);
}
StringBuilder.prototype.toString = function () {
return this.__strings__.join("");
}
var beginDate2 = new Date();
var builder = new StringBuilder();
for (var i = 0; i < 100000; i++) {
builder.append("text");
}
var result = builder.toString();
var endDate2 = new Date();
document.write("方法二:数组拼接,耗时:" + (endDate2.getTime() - beginDate2.getTime()) + "毫秒<br/>");
</script>
</head>
<body>
</body>
</html>
《javascript高级程序设计》一书上说,直接拼接字符串会造成性能问题,应该采用Array对象存储字符串,然后用join()方法创建最后的字符串。说可以节省50%~66%的时间,但是我测试发现,用数组拼接的方式往往还更耗时,如何解释呢?