<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
_.sum(arr)
arr.reduce((a, c) => a + c, 0)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
sum | |
reduce |
Test name | Executions per second |
---|---|
sum | 12114563.0 Ops/sec |
reduce | 7794321.5 Ops/sec |
The benchmark being tested here compares two methods of summing an array of numbers in JavaScript: using the Lodash library's _.sum
method and the native array method reduce
.
_.sum(arr)
: This method uses the Lodash library to compute the sum of elements in the given array arr
.arr.reduce((a, c) => a + c, 0)
: This native JavaScript approach leverages the built-in reduce
method of arrays to achieve the same result._.sum(arr)
Pros:
Cons:
arr.reduce((a, c) => a + c, 0)
Pros:
Cons:
reduce
could potentially be less efficient, though in many cases this is negligible due to JavaScript engine optimizations.From the benchmark results, we see:
_.sum
) executions per second: 11,819,274.0This indicates that using the native reduce
method is significantly more efficient in this case, roughly 5.7 times faster than using _.sum
.
Apart from the two methods covered in the benchmark, other alternatives to sum an array in JavaScript include:
for
loop can be used to iterate through the array and keep a running total.forEach
to iterate and sum values, although typically less efficient than reduce
.Int32Array
, Float64Array
) can enhance performance, especially for large datasets.The choice between these methods often depends on the specific requirements of the project, including performance considerations, readability preference, and the existing codebase dependencies.