Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1102300
  • 博文数量: 1310
  • 博客积分: 3980
  • 博客等级: 中校
  • 技术积分: 8005
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-09 22:05
文章分类

全部博文(1310)

文章存档

2011年(1)

2008年(1309)

我的朋友

分类:

2008-11-09 17:41:18

在做大字符串连接时,常用 += 来连接字符串,但这种连接符的效率随着字符串的增大迅速降低,比如下面输出1000个5行5列的表格:

<script>
var d1 = new Date();
var str = "";
for (i=0; i<1000; i++){
 str 
+= ""300" border="1" cellpadding="5" cellspacing="1">  123451122
334455111222333
4445551111222233334444
555511111222223333344444
55555
"
}
document.write(str)
var d2 = new Date();
alert(d2
-d1);
script>
我的硬件配置使用 +=的连接办法约需要1950毫秒。

在前面几篇日志已经证明到,大字符串的连接最好使用数组,把每个子串放入数组元素,再执行join()连接起来,其效率比+=有明显的提高。

因此,可以由此原理写一个简单的 StringBuffer 类,在遇到大字符串连接时可以派上用场。

function StringBuffer(){
this.data = [];
}
StringBuffer.prototype.append 
= function(){
this.data.push(arguments[0]);
return this;
}
StringBuffer.prototype.toString 
= function(){
return this.data.join("");
}


代码很简单,再应用到上面的例子,看看执行时间要多少:
<script>
function StringBuffer(){
 
this.data = [];
}
StringBuffer.prototype.append 
= function(){
 
this.data.push(arguments[0]); 
}
StringBuffer.prototype.toString 
= function(){
 
return this.data.join("");
}
var d1 = new Date();
var a = new StringBuffer();
for (i=0; i<1000; i++){
 a.append(
""300" border="1" cellpadding="5" cellspacing="1">  123451122
334455111222333
4445551111222233334444
555511111222223333344444
55555
");

 

document.write(a.toString())

var d2 = new Date();
alert(d2
-d1);
script>
结果是耗时431毫秒,是+=连接方法效率的4~5倍。

Yemoo'S JS Blog 2007-07-04 08:41 发表评论
阅读(237) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~