<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var arr = [];
for(var i = 0; i < 100000; i++){
arr.push({value:getRandomInt(100)});
}
_.sumBy(arr, "value");
arr.reduce((prev, next) => prev + next.value, 0);
_.sumBy(arr, x => x.value);
let result = 0;
for(const x of arr) {
result += x.value;
}
let result = 0;
for(let i = 0; i < arr.length; i++) {
result += arr[i].value;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.sumBy value | |
map and reduce | |
_.sumBy with map | |
sum with for of loop | |
sum with for loop |
Test name | Executions per second |
---|---|
_.sumBy value | 1376.9 Ops/sec |
map and reduce | 6770.3 Ops/sec |
_.sumBy with map | 1371.2 Ops/sec |
sum with for of loop | 10215.6 Ops/sec |
sum with for loop | 4320.7 Ops/sec |
Measuring the performance of different JavaScript methods can be quite fascinating, especially when it comes to summing values in an array.
In this benchmark, we have four test cases that compare three different approaches:
sumBy
: A utility function provided by the popular Lodash library, which allows you to sum a property of each element in an array.reduce
method along with map
to achieve the same result as sumBy
.for of
): A simple, imperative approach using a for loop to iterate over the array and sum up the values.Let's dive into each option:
Lodash sumBy
Pros:
Cons:
The sumBy
function takes two arguments: the array to sum, and a callback function that extracts the value from each element. The callback function is called for each element in the array, and its return value is added together.
_.sumBy(arr, "value");
Reduce with map
Pros:
Cons:
sumBy
The reduce method takes an initial value (in this case, 0), and applies a callback function to each element in the array. The callback function sums up the values as it iterates through the array.
arr.reduce((prev, next) => prev + next.value, 0);
For loop (using for of
)
Pros:
Cons:
This approach uses a for loop with the of
keyword to iterate over the array and sum up the values.
for (const x of arr) {
result += x.value;
}
Now, let's talk about the latest benchmark results:
The top-performing test case is "sum with for of loop", which executes approximately 160 executions per second. This suggests that the for loop approach is relatively fast and efficient.
In contrast, the other three approaches are slower:
sumBy
: Executes around 140-150 executions per secondOther alternatives to consider:
Array.prototype.reduce()
without using the map
functionKeep in mind that benchmarking results can vary depending on the specific test environment, hardware, and version of JavaScript being used.