// Purposely global
numbers = Array.from({length: 1e6}, () => Math.floor(Math.random() * 1e20))
function findMode(numbers) {
let counted = numbers.reduce((acc, curr) => {
if (curr in acc) {
acc[curr]++;
} else {
acc[curr] = 1;
}
return acc;
}, {});
let mode = Object.keys(counted).reduce((a, b) => counted[a] > counted[b] ? a : b);
return mode;
}
function mostCommonNumber(numbers) {
let map = new Map()
for (let num of numbers) {
map.set(num, (map.get(num) || 0) + 1)
}
let mostCommonNumber = NaN
let maxCount = -1
for (let [num, count] of map.entries()) {
if (count > maxCount) {
maxCount = count
mostCommonNumber = num
}
}
return mostCommonNumber
}
findMode(numbers)
mostCommonNumber(numbers)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findMode | |
mostCommonNumber |
Test name | Executions per second |
---|---|
findMode | 0.4 Ops/sec |
mostCommonNumber | 1.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared options, pros and cons, and other considerations.
Benchmark Overview
The benchmark consists of two test cases: findMode
and mostCommonNumber
. Both functions are designed to find the mode (the most frequently occurring value) in an array of numbers. The tests compare the performance of these two implementations.
Implementation Comparison
The two implementations differ in their approach:
Object.keys
and reduce
) to count the occurrences of each number. It then finds the key with the highest value.Map
object. It iterates through the numbers, incrementing the count for each unique number.Pros and Cons
Object.keys
, which has a higher overhead than using an array-based approach.Other Considerations
Array.from
and Math.random
, which ensures that the results are not deterministic.Special JS Features
In this benchmark, we don't see any special JavaScript features being used. However, some other benchmarks might use features like:
These features can introduce additional overhead or complexities, making it harder to compare performance results.
Alternative Implementations
If you're interested in exploring alternative implementations, here are a few examples:
Keep in mind that these alternative implementations might not be as efficient or scalable as the original findMode
and mostCommonNumber
implementations.