var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
arr.filter(x => x % 30).map(x => x/100)
arr.flatMap(x => x % 30 ? x/100 : [])
var accum = [];
for (let i=0; i < arr.length; i++) {
const x = arr[i];
if (x % 30) { accum.push(x/100) }
}
var accum = [];
arr.forEach((x) => {
if (x % 30){ accum.push(x/100) }
})
var accum = [];
for (const x of arr) {
if (x % 30) { accum.push(x/100) }
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter().map() | |
flatMap() | |
for loop | |
forEach | |
for of loop |
Test name | Executions per second |
---|---|
filter().map() | 263.9 Ops/sec |
flatMap() | 267.7 Ops/sec |
for loop | 503.8 Ops/sec |
forEach | 349.5 Ops/sec |
for of loop | 518.6 Ops/sec |
The benchmark is designed to compare the performance of various JavaScript approaches for filtering and mapping a large array of numbers. The key focus is on how each of the following methods handles the operations:
filter().map()
: A functional approach using two separate array methods.flatMap()
: A method that combines mapping and flattening operations.for loop
: A traditional loop that accumulates results into a new array.forEach
: An array iteration method that executes a provided function once for each array element.for of loop
: A newer syntax for looping through iterable objects, like arrays.filter().map()
:
x % 30
), then maps the remaining elements from their original values to divided by 100.flatMap()
:
filter().map()
because it avoids the second iteration through the array.for loop
:
forEach
:
for of loop
:
forEach
, but provides a cleaner and more efficient way to iterate.for
loops depending on the implementation.From the benchmark results executed with various JavaScript engines, the execution speeds appear as follows:
for of loop
: 1931.07 Executions/Second (highest performance)for loop
: 1440.99 Executions/SecondforEach
: 810.59 Executions/SecondflatMap()
: 582.91 Executions/Secondfilter().map()
: 461.33 Executions/Second (lowest performance)for of loop
or for loop
.filter().map()
or flatMap()
can be beneficial, particularly for developers familiar with functional programming concepts.Other alternatives could include:
reduce()
that can accumulate values in a single pass but may introduce complexity.Ultimately, the best approach depends on the specific context of the project—such as dataset size requirements for speed, code clarity preferences for maintainability, and developer familiarity with different JavaScript constructs.