Fastest JavaScript summation

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

    Improvements


    Your looping structure could be made faster:


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

    This retrieves array.length once, rather than with each iteration. The optimization is made by caching the value.


    If you really want to speed it up:


       var count=0;
       for (var i=array.length; i--;) {
         count+=array[i];
       }
    

    This is equivalent to a while reverse loop. It caches the value and is compared to 0, thus faster iteration.

    For a more complete comparison list, see my JSFiddle.
    Note: array.reduce is horrible there, but in Firebug Console it is fastest.


    Compare Structures

    I started a JSPerf for array summations. It was quickly constructed and not guaranteed to be complete or accurate, but that's what edit is for :)

提交回复
热议问题