var array = Array.from({ length: 10000 }, () => Math.floor(Math.random() * 10000))
array.forEach(n => {
const repeat = Math.sqrt(n);
const result = [[], []];
for (let i = 1; i <= repeat; i++) {
if(n % i === 0) {
result.push(i);
if (i !== repeat) result.push(n / i);
}
}
result.sort((a, b) => a - b)
}
)
array.forEach(n => {
const repeat = Math.sqrt(n);
const result = [[], []];
for (let i = 1; i < repeat; i++) {
if(n % i === 0) {
result[0].push(i);
result[1].push(n / i);
}
}
if (Number.isInteger(repeat)) result[0].push(repeat)
result[1].reverse();
result.flat()
}
)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
sort | |
reverse |
Test name | Executions per second |
---|---|
sort | 38.9 Ops/sec |
reverse | 73.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark is designed to compare two approaches for reversing and sorting an array of numbers in JavaScript:
Array.prototype.sort()
method, which sorts the array in place using a stable sorting algorithm (Timsort).Test Case Explanation
For each test case, here's what's being tested:
Array.from()
. It then defines a script that uses the forEach()
method to iterate over the array. Inside the loop:repeat
.result[0]
and result[1]
) to store divisors and quotients, respectively.repeat
, checking if n
is divisible by i
. If so, it pushes both i
and the quotient n / i
into their respective arrays. After the loop, it sorts the combined array using Array.prototype.sort()
.repeat
, just like the first test case.result[1]
). Then, it reverses this array using the reverse()
method. Finally, it flattens the resulting array using the flat()
method.Library and Special Features
Options Compared
The two test cases compare the performance of:
Array.prototype.sort()
method, which is implemented in the browser's engine.Pros and Cons
Other Alternatives
If you wanted to explore alternative approaches, here are a few options:
Array.prototype.map()
instead of forEach()
.Keep in mind that these alternatives might change the benchmark's behavior and results.