您的位置:首页 > Web前端 > JavaScript

比较javascript两种字符串连接的性能

2009-04-11 20:50 591 查看
(1)使用‘+’连接

   var str="hello";

   str+="world";

代码在后台执行的步骤:

1.创建存储"hello"的字符串。

2.创建存储"world"的串。

3.创建存储连接结果的字符串。

4.把str的当前内容复制到结果中。

5.把"world"复制到结果中。

6.更新str,使它指向结果。

每完成字符串连接都会执行步骤2到6,很耗资源,如果重复这一过程几百次,甚至几千次就会造成性能问题!

(2)使用Array对象和join()

  var arr=new Array();

 arr[0]="hello";

 arr[1]="world";

 var str=arr.join("");

执行的步骤:

1.创建存储结果的字符串。

2.把每个字符串复制到结果的中的适合位置。

只有在调用join()方法的时候才会发生连接操作。

 

仿StringBuffer的例子

<!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>
<mce: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("");
}
window.onload=function(){
var d1=new Date();
var str="";
for(var i=0;i<1000;i++){
str+="text";
}
var d2=new Date();
document.write("concatenttion with plus:"+(d2.getTime()-d1.getTime())+"millisecnds");
var oBuffer=new StringBuffer();
d1=new Date();
for(var i=0;i<1000;i++){
oBuffer.append("text");
}
var sResult=oBuffer.toString();
var d2=new Date();
document.write("<br/>concatenttion with stringbuffer:"+(d2.getTime()-d1.getTime())+"millisecnds");
}
// --></mce:script>
</head>
<body>
</body>
</html>


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息