Fastest JavaScript summation

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

    What about summing both extremities? It would cut time in half. Like so:

    1, 2, 3, 4, 5, 6, 7, 8; sum = 0

    2, 3, 4, 5, 6, 7; sum = 10

    3, 4, 5, 6; sum = 19

    4, 5; sum = 28

    sum = 37

    One algorithm could be:

    function sum_array(arr){
        let sum = 0,
            length = arr.length,
            half = Math.floor(length/2)
    
        for (i = 0; i < half; i++) {
            sum += arr[i] + arr[length - 1 - i]
        }
        if (length%2){
            sum += arr[half]
        }
        return sum
    }
    

    It performs faster when I test it on the browser with performance.now(). I think this is a better way. What do you guys think?

提交回复
热议问题