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

來源:互聯網
上載者:User
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    /*
15        1.建立儲存'hello'的字串
16        2.建立儲存'world'的字串
17        3.建立儲存連結結果的字串
18        4.把str的當前內容複寫到結果中
19        5.把'world'複製到結果中
20        6.更新str,使它指向結果
21    */    
22    
23    //為了提高效能最好使用數組方法拼接字串
24    //建立一個StringBuffer類
25    function StringBuffer(){
26        this.__strings__ = [];
27    };    
28    StringBuffer.prototype.append = function(str){
29        this.__strings__.push(str);
30    };
31    StringBuffer.prototype.toString = function(){
32        return this.__strings__.join('');
33    };
34    
35    //調用StringBuffer類,實現拼接字串
36    //每次完成字串串連都會執行步驟2步
37    //實際上,這段代碼在幕後執行的步驟如下:
38    /*
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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.