// Purposely global
numbers = Array.from({length: 1e6}, () => Math.floor(Math.random() * 1e5))
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 | 12.0 Ops/sec |
mostCommonNumber | 7.1 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The JSON represents two JavaScript microbenchmarks: findMode
and mostCommonNumber
. Both functions take an array of numbers as input and return the most frequently occurring number in the array.
Options Compared
For each benchmark, two options are compared:
Map
object to count the occurrences of each number in the array. This approach is implemented in the findMode
function.Map
object and instead uses an object literal to store the counts. This approach is implemented in the mostCommonNumber
function.Pros and Cons
Using a Map (findMode)
Pros:
Cons:
Without Using a Map (mostCommonNumber)
Pros:
Cons:
In general, using a Map
object is a good choice when working with large datasets or performance-critical applications. However, it may come at the cost of higher memory usage.
Library
The Array.from()
method is used in both benchmarks to create an array of random numbers. This method is a part of the ECMAScript standard and is supported by most modern JavaScript engines.
Special JS Feature/Syntax
None of the tested code uses any special JavaScript features or syntax that would make it non-standard or non-portable.
Alternatives
If you need to optimize these benchmarks further, here are some alternative approaches:
Set
object instead of a Map
object for counting occurrences.Keep in mind that optimization should always be done carefully and with a clear understanding of the trade-offs involved.