重拾Javascript(五)--优化字符串操作

连接字符串

var str = "hello ";
str += "world";
很简单的两句代码,内存会执行如下步骤:

  • 创建存储"hello "的字符串
  • 创建存储"world"的字符串
  • 创建存储结果的字符串
  • 把str的当前内容复制到结果中
  • 把"world"复制到结果中
  • 更新str,使他指向结果

每次完成完成字符串连接都会执行步骤2到6,使得这种操作非常消耗资源。如果重复这一过程几千次,就会造成性能问题。我们可以用Array对象存储字符串,然后用join方法创建最后的字符串。Javascript里面的数组最多可以存放4294967295项。考虑如下代码
var arr = new Array();
arr[0] = "hello ";
arr[1] = "world";
var str = arr.join("");

我们可以参考C#里面的StringBuilder类,将这个功能封装起来:
function StringBuilder()
{
  this.strings = new Array();
}

StringBuilder.prototype.append = function(str)
{
  this.strings.push(str);
}; 

StringBuilder.prototype.toString = function()
{
  this.strings.join("");
};

var sBuilder = new StringBuilder();
sBuilder.append("hello ");
sBuilder.append("world");
var str = sBuilder.toString();

 

新写的版本,支持扩展数组。

 

(function ()
{
    function StringBuffer(strVal)
    {
        this.temArr = [];
        if (typeof strVal === "string")
        {
            this.temArr.push(strVal)
        }
    }

    StringBuffer.prototype.append = function (argVal)
    {
        var toString = Object.prototype.toString;

        if (typeof argVal === "string")
        {
            this.temArr.push(argVal);
        }

        if (toString.call(argVal) === "[object Array]")
        {
            this.temArr = this.temArr.concat(argVal);
        }
    }

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

})();

 

 

 

 

 

posted @ 2009-09-28 17:42  逆天寒  阅读(238)  评论(0编辑  收藏  举报