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

本文探讨了JavaScript中字符串拼接的效率问题,指出直接使用加号进行字符串拼接会导致性能下降,并提供了一种利用数组和join方法来提高字符串拼接效率的方法。此外,还介绍了两种自定义StringBuilder类的方法。

连接字符串

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("");
    }

})();

 

 

 

 

 

转载于:https://www.cnblogs.com/AndrewZhang/archive/2009/09/28/1575842.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值