Fastest JavaScript summation

前端 未结 10 2024
再見小時候
再見小時候 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.

    0 讨论(0)
  • 2020-11-27 15:38

    You should be able to use reduce.

    var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);
    

    Source

    And with arrow functions introduced in ES6, it's even simpler:

    sum = array.reduce((pv, cv) => pv + cv, 0);
    
    0 讨论(0)
  • 2020-11-27 15:39

    The fastest loop, according to this test is a while loop in reverse

    var i = arr.length; while (i--) { }
    

    So, this code might be the fastest you can get

    Array.prototype.sum = function () {
        var total = 0;
        var i = this.length; 
    
        while (i--) {
            total += this[i];
        }
    
        return total;
    }
    

    Array.prototype.sum adds a sum method to the array class... you could easily make it a helper function instead.

    0 讨论(0)
  • 2020-11-27 15:40

    one of the simplest, fastest, more reusable and flexible is:

    Array.prototype.sum = function () {
        for(var total = 0,l=this.length;l--;total+=this[l]); return total;
    }
    
    // usage
    var array = [1,2,3,4,5,6,7,8,9,10];
    array.sum()
    
    0 讨论(0)
提交回复
热议问题