Fastest JavaScript summation

前端 未结 10 2136
再見小時候
再見小時候 2020-11-27 15:13

What is the fastest way to sum up an array in JavaScript? A quick search turns over a few different methods, but I would like a native solution if possible. This will run un

10条回答
  •  爱一瞬间的悲伤
    2020-11-27 15:35

    Based on this test (for-vs-forEach-vs-reduce) and this (loops)

    I can say that:

    1# Fastest: for loop

    var total = 0;
    
    for (var i = 0, n = array.length; i < n; ++i)
    {
        total += array[i];
    }
    

    2# Aggregate

    For you case you won't need this, but it adds a lot of flexibility.

    Array.prototype.Aggregate = function(fn) {
        var current
            , length = this.length;
    
        if (length == 0) throw "Reduce of empty array with no initial value";
    
        current = this[0];
    
        for (var i = 1; i < length; ++i)
        {
            current = fn(current, this[i]);
        }
    
        return current;
    };
    

    Usage:

    var total = array.Aggregate(function(a,b){ return a + b });
    

    Inconclusive methods

    Then comes forEach and reduce which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.

提交回复
热议问题