在JavaScript中使用StringBuilder

來源:互聯網
上載者:User

介紹:
在不久以前,將一些主要操作,尤其在用戶端瀏覽器中的操作被認為是很困難的。現在流行的AJAX下做的各種開發應用,迅速成為一種熱門的技術。但是,市場上大多數瀏覽器是在字串串連上處理速度並不理想。
一個好訊息是雖然IE對字串串連處理緩慢,但字元操作上速度已經是最快的了。由於這個原因,我決定寫一個簡單的StringBuilder類將獨立的字串儲存到一個數組裡,然後用join方法執行串連輸出操作。在測試裡我用了5000個字串,比等價運算s1 += s2快了117次。當加到10000個字串後,快了261次。

//引入一個StringBuilder類的新對象
//附加提供了的給定值
function StringBuilder(value)
{
    this.strings = new Array("");
    this.append(value);
}

//在對象後咐給指定值
StringBuilder.prototype.append = function (value)
{
    if (value)
    {
        this.strings.push(value);
    }
}

//清楚字元緩衝
StringBuilder.prototype.clear = function ()
{
    this.strings.length = 1;
}

//用字串轉化對象
StringBuilder.prototype.toString = function ()
{
    return this.strings.join("");
}

The code is so simple and straightforward that it should be self-explanatory. Now here's an example of how to use it:
代碼看上去很簡單,直接。有自我說明性,以下是如何使用該類

//建立一個StringBuilder對象
var sb = new StringBuilder();

//賦一些字串
sb.append("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, ");
sb.append("sed diem nonummy nibh euismod tincidunt ut lacreet dolore ");
sb.append("magna aliguam erat volutpat.");

//獲得所有字元值
var s = sb.toString();

仍然非常簡單直接,不需要太多的說明。如果你在.NET中用了StringBuilder,你也回知道這裡如何用。
在HTML中實現了邊到邊的比較。你可以用它設計一些測試,看看有什麼不同。在我機器上,串連5000個字元需要12秒。StringBuilder只用了110 毫秒。10000個字串,將佔用IE所有時鐘。StringBuilder只需要230毫秒。每一秒減少四分之一秒,這是一個顯著的提高。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.