根据电脑配置,多浏览器

先贴出完整代码.

书中附带的测试代码如下 

复制代码 代码如下:

复制代码 代码如下:

<script type=”text/javascript”>
function StringBuffer() {
this._strings = new Array();
}
StringBuffer.prototype.append = function(str) {
this._strings.push(str);
//StringBuffer.prototype.length =
this._strings.length;//每多一行,就会多消耗处理时间
var i = “asdfasdf”;
}
StringBuffer.prototype.toString = function() {
this._strings.join(“”);
}
/*String类 + 号累加*/
var d = new Date();//累加开始时间
var str = “1”;
for (var i = 0; i < 200; i++) {
str += “ssss”;
for (var i = 0; i < 30000; i++) {
str += “text”;
}
}
var d2 = new Date(); //累加结束时间
document.write(“+:”+(d2.getTime() – d.getTime()) +
“milliseconds”);//累加30000用时
/*自定义StringBuffer类 字符串累加*/
d = new Date(); //StringBuffer开始时间
var buffer = new StringBuffer();
for (var i = 0; i < 200; i++) {
str += “ssss”;
for (var i = 0; i < 30000; i++) {
buffer.append(“text”);
}
}
var resultstr = buffer.toString();
d2 = new Date();
document.write(“<br/>StringBuffer:” + (d2.getTime() –
d.getTime()) + “milliseconds”);
/*直接使用Array 不进行封装*/
d = new Date();
var arr = new Array();
for (var i = 0; i < 200; i++) {
str += “ssss”;
for (var i = 0; i < 30000; i++) {
arr.push(“text”);
}
}
var resStr = arr.join(“”);
d2 = new Date();
document.write(“<br/>Array:” + (d2.getTime() – d.getTime()) +
“milliseconds”);
</script>
[code]

<html>
<head>
<title>Example</title>
</head>
<body>
<p><strong>Note:</strong> The latest versions of
Firefox seem to have fixed the string concatenation problem. If you are
using Firefox 1.0 or later, the string buffer may actually take longer
than normal string concatenation.</p>
<script type=”text/javascript”>
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 < 10000; 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 < 10000; i++) {
buffer.append(“text”);
}
var result = buffer.toString();
d2 = new Date();
document.write(“<br />Concatenation with StringBuffer: ” +
(d2.getTime() – d1.getTime()) + ” milliseconds”);
</script>

先说下我的机器配置 如图1:
图片 1

</body>
</html>