Fastest JavaScript summation

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

提交回复
热议问题