var arr = Array.from({ length: 10000 }, Math.random);
var TARGET_VALUE = 0.95;
function* filter(iter, f) {
for (const it of iter) {
if (f(it)) {
yield it;
}
}
}
return arr.filter(x => x >= TARGET_VALUE);
const farr = [];
for (let i = 0, len = arr.length; i < len; ++i) {
if (arr[i] < TARGET_VALUE) {
continue;
}
farr.push(arr[i]);
}
return farr;
const farr = [];
for (let i = 0, len = arr.length; i < len; ++i) {
if (arr[i] >= TARGET_VALUE) {
farr.push(arr[i]);
}
}
return farr;
const farr = [];
for (const x of arr) {
if (x >= TARGET_VALUE) {
farr.push(x);
}
}
return farr;
return arr.reduce(
(a, b) => {
if (b >= TARGET_VALUE) {
a.push(b);
}
return a;
},
[],
);
return [filter(arr, x => x >= TARGET_VALUE)];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.filter | |
for, continue | |
for, condition | |
for..of | |
Array.reduce | |
generator, spread |
Test name | Executions per second |
---|---|
Array.filter | 2091.5 Ops/sec |
for, continue | 1076.3 Ops/sec |
for, condition | 1078.1 Ops/sec |
for..of | 1932.6 Ops/sec |
Array.reduce | 2084.1 Ops/sec |
generator, spread | 1786.7 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of different approaches for filtering an array in JavaScript:
Array.filter
continue
statementfor..of
loopArray.reduce
methodOptions Compared
The benchmark compares the performance of each option across multiple executions, providing an idea of which approach is faster in different scenarios.
Pros and Cons of Each Approach
Array.filter
:continue
statement:Array.filter
and may be slower.for..of
loop:Array.prototype.forEach()
.Array.reduce
method:Additional Considerations
Array.filter
method is expected to be slower than other approaches because it creates an intermediate array with the filtered elements.continue
, as they allow for more precise control over individual elements.for..of
loops are a concise way to iterate over arrays, but their behavior may differ when used with array-like objects or prototype chains.Array.reduce
method is useful when working with accumulators or functional programming principles.Benchmark Results
The provided benchmark results show the execution rate (executions per second) for each option. The top three performers are:
for..of
loop: 1932 executions/secondcontinue
statement: 1078 executions/secondNote that these results may vary depending on the specific use case, array size, and JavaScript engine being used.
Overall, the benchmark highlights the importance of choosing an efficient approach for filtering arrays in JavaScript, taking into account factors like readability, maintainability, and performance.