JavaScript:利用StringBuffer类提升+=拼接字符串效率

1 <! DOCTYPE html PUBLIC  " -//W3C//DTD XHTML 1.0 Transitional//EN "  " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd " >
 2 < html xmlns = " http://www.w3.org/1999/xhtml " >
 3 < head >
 4 < meta http - equiv = " Content-Type "  content = " text/html; charset=utf-8 "  / >
 5 < title >< / title>
 6 < / head>
 7 < body >
 8 < / body>
 9 < script type = " text/javascript " ><!--
10      var  str  =  ' hello ' ;
11     str  +=  ' world ' ;
12      // 每次完成字符串连接都会执行步骤2到6步
13      // 实际上,这段代码在幕后执行的步骤如下:
14 ExpandedBlockStart.gifContractedBlock.gif      /*
15        1.创建存储'hello'的字符串
16        2.创建存储'world'的字符串
17        3.创建存储链接结果的字符串
18        4.把str的当前内容复制到结果中
19        5.把'world'复制到结果中
20        6.更新str,使它指向结果
21    */
    
22     
23      // 为了提高性能最好使用数组方法拼接字符串
24      // 创建一个StringBuffer类
25 ExpandedBlockStart.gifContractedBlock.gif      function  StringBuffer() {
26        this.__strings__ = [];
27    }
;    
28 ExpandedBlockStart.gifContractedBlock.gif    StringBuffer.prototype.append  =  function (str) {
29        this.__strings__.push(str);
30    }
;
31 ExpandedBlockStart.gifContractedBlock.gif    StringBuffer.prototype.toString  =  function () {
32        return this.__strings__.join('');
33    }
;
34     
35      // 调用StringBuffer类,实现拼接字符串
36      // 每次完成字符串连接都会执行步骤2步
37      // 实际上,这段代码在幕后执行的步骤如下:
38 ExpandedBlockStart.gifContractedBlock.gif      /*
39        1.创建存储结果的字符串
40        2.把每个字符串复制到结果中的合适位置
41    */

42      var  buffer  =  new  StringBuffer();
43     buffer.append( ' hello  ' );
44     buffer.append( ' world ' );
45      var  result  =  buffer.toString();
46     
47      // 用StringBuffer类比使用+=节省50%~66%的时间
48 // -->
49 < / script>
50 < / html>
51
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值