function searchMostCommonNumber(arr) {
if (arr === void 0) {
arr = [];
}
var current = 0;
var max = 0;
var mostCommonNumber = 0;
var i;
for (i = 0; i < arr.length - 1; i++) {
var current_1 = 1;
var j = void 0;
for (j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
current_1++;
}
}
if (current_1 > max) {
max = current_1;
mostCommonNumber = arr[i];
}
}
return mostCommonNumber;
}
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
}
numbers = Array(1e2).map(n => Math.floor(Math.random() * 1000))
searchMostCommonNumber(numbers)
mostCommonNumber(numbers)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
searchMostCommonNumber | |
mostCommonNumber |
Test name | Executions per second |
---|---|
searchMostCommonNumber | 6758.5 Ops/sec |
mostCommonNumber | 131856.2 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Definition JSON
The benchmark definition is represented as a JavaScript function that calculates the most common number in an array of numbers. The function has two implementations:
searchMostCommonNumber(arr)
: This function iterates through the array, counting the occurrences of each number. It keeps track of the maximum count and returns the corresponding number.mostCommonNumber(numbers)
: This function uses a Map data structure to count the occurrences of each number in the array. It then finds the key with the maximum value in the map.Options Compared
The two functions are compared in terms of their performance, which is measured by the "ExecutionsPerSecond" metric. This metric represents how many times each function executes per second.
Pros and Cons of Each Approach
searchMostCommonNumber(arr)
:mostCommonNumber(numbers)
:Library/Functionality Used
Both functions use JavaScript's built-in Array
and Math
objects. The second function also uses a Map
object from the JavaScript Standard Library, which is available in modern browsers and Node.js environments.
Special JS Feature/Syntax (Not Applicable)
There are no special JavaScript features or syntax used in these benchmark functions.
Other Alternatives
Some alternative approaches could be:
Keep in mind that these alternatives may not be relevant to this specific benchmark and might require additional changes to the code.