var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const counts = {};
for (const num of arr) {
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
arr.reduce(function (acc, curr) {
return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc
}, {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
reduce |
Test name | Executions per second |
---|---|
for | 2758683.0 Ops/sec |
reduce | 1429770.5 Ops/sec |
Let's break down the provided JSON and explain what is being tested.
What is being tested?
MeasureThat.net is testing two different approaches to count the occurrences of each number in an array: for
loop and reduce()
method.
Options compared
The for
loop approach iterates over the array using a traditional for
loop, incrementing a counter for each element. The reduce()
method, on the other hand, uses the Array.prototype.reduce() method to accumulate the counts in an object.
Pros and Cons of each approach:
reduce()
method, especially for large arrays.for
loop approach.reduce()
method syntax, which can be unfamiliar to some developers.Library and its purpose
In this benchmark, no specific library is used. However, it's worth noting that the reduce()
method is a built-in JavaScript method that was introduced in ECMAScript 2011 (ES6). It provides a concise way to accumulate values in an accumulator object.
Special JS feature or syntax
No special features or syntax are being tested in this benchmark. The code uses standard JavaScript syntax and does not rely on any advanced features like async/await, Promises, or async/async functions.
Other alternatives
If the for
loop approach were not used, alternative approaches could include:
forEach()
method with a callback function to iterate over the array.map()
method in combination with the reduce()
method to achieve similar results.However, it's worth noting that these alternatives may not provide significant performance improvements over the for
loop approach for small to medium-sized arrays.