<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.0/underscore.js"></script>
var data = {};
Array(10000).keys().forEach(function (i) {
data[i] = i;
});
var result = 0
_.each(data, (i) => {result += i})
var result =
Object.values(data).forEach((i) => {result += i})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Underscore | |
Native |
Test name | Executions per second |
---|---|
Underscore | 11119.5 Ops/sec |
Native | 21260.5 Ops/sec |
Let's dive into the world of MeasureThat.net and analyze the provided benchmark.
Benchmark Overview
The benchmark is designed to measure the performance difference between using Underscore.js (a popular JavaScript utility library) versus native JavaScript for iterating over an array using forEach
. The test creates a large array of 10,000 elements, assigns each element a value, and then measures how long it takes to sum up all these values using both approaches.
Test Cases
There are two test cases:
each
function to iterate over the array and accumulate the sum.forEach
method to iterate over the array and accumulate the sum.Comparison
The main difference between these two approaches is how they handle the iteration and accumulation of values.
_.each
iterates over the array and calls a callback function for each element, which accumulates the sum in the result
variable.forEach
method is more direct and explicit. It iterates over the array and calls a provided callback function for each element, but does not accumulate values by default. In this case, we need to explicitly use Object.values(data).forEach((i) => { result += i })
to achieve the same result.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Object.values()
and forEach
)Other Considerations
When writing benchmarks, it's essential to consider the following factors:
Alternatives
If you were to rewrite this benchmark without using Underscore.js, you could consider alternative libraries or approaches for iterating over arrays, such as:
map()
and reduce()
methodsKeep in mind that the choice of alternative will depend on the specific requirements and constraints of your benchmark.