var arr = Array.from({ length: 10000 }, Math.random);
var TARGET_VALUE = 0.95;
function* filter(iter, f) {
for (const it of iter) {
if (f) {
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 | 22628.4 Ops/sec |
for, continue | 85237.8 Ops/sec |
for, condition | 79578.9 Ops/sec |
for..of | 22083.7 Ops/sec |
Array.reduce | 27311.7 Ops/sec |
generator, spread | 2238.9 Ops/sec |
I'll break down the benchmark and its test cases for you.
Benchmark Overview
The benchmark compares four different approaches to filter an array of 10,000 random numbers:
Array.filter()
for
loop with continue
for
loop without continue
for...of
loopArray.reduce()
[...generator()]
)Library and Special JS Features
const
, let
, var
with Destructuring assignment.Test Case Analysis
Here's a brief analysis of each test case:
for
loop iterates over the array using an index variable, checking each element against the target value and skipping it if necessary.continue
.for
loop uses the for...of
construct to iterate over the array, which is more concise and expressive than traditional indexing.yield
and ...
to create an iterable sequence that can be converted to an array using the spread operator ([...]
).Comparison
The benchmark measures the execution speed of each approach, with Chrome 114 as the executing browser. The results show that:
Array.filter()
is faster than traditional loops (both for, continue
and for, condition
)For...of
loop is slower than Array.filter()
Array.reduce()
is slowest among all approachesInterpretation
The results suggest that:
Array.filter()
method is efficient due to its optimized implementation.for, continue
and for, condition
) are slower but still suitable for smaller datasets or when specific control flow is required.Keep in mind that this benchmark is specific to Chrome 114 and may not generalize to other browsers or environments.