一、背景(字符串连接)

C#与JavaScript一样,使用+来连接字符串。事实上,这种字符串拼接方式是非常消耗资源的,当这种操作的重复次数较多时(成百上千),会造成性能问题。在 C# 中,可以使用 StringBuffer 来应对大量的字符串拼接操作,在 JavaScript 中呢?默认没有这样的StringBuffer类,不过可以自己写个 StringBuffer 类。

二、解决方案

StringBuffer类源码:

    function StringBuffer() {
        this.__strings__ = new Array();
    if (typeof StringBuffer._initialized == "undefined") {
        StringBuffer.prototype.append = function (s) {
            this.__strings__.push(s);
        };

        StringBuffer.prototype.appendLine = function (s) {
            this.__strings__.push(s + "\n");
        };

        StringBuffer.prototype.toString = function () {
            return this.__strings__.join("");
        };

        StringBuffer._initialized = true;
    }
}</pre>

三、原理剖析

以上代码使用了Array对象存储字符串,然后使用join()方法(参数是空字符串)拼接成最后的字符串。这样子在数组中引入多少字符串都不成问题,因为只有在调用join()方法时才会发生连接操作。(我猜C#中的StringBuffer也是这样实现的)

JavaScript中并没有class这样的定义类的关键字,以上使用了动态原型的途径来模拟了类的实现。

四、应用示例

点击这里运行

    var sb = new StringBuffer();
    sb.append("hello");
    sb.append(", I'm ");
    sb.appendLine("Jeff");
    sb.appendLine("It's great day for love, isn't it?");
    sb.appendLine("Welcome to www.zizhujy.com!");
alert(sb.toString());</pre>

[donate: www.zizhujy.com]