<!--your preparation HTML code goes here-->
var elements = Array.from({length:100}).map(() => Math.floor(Math.random() * 1000));
const result = [];
for (let i = 0; i < elements.length; i++) {
if (elements[i] % 5 === 0) {
result.push(elements[i] * 2);
}
}
const result = [];
for (let element of elements) {
if (element % 5 === 0) {
result.push(element * 2);
}
}
const result = [];
elements.filter(element => element % 5 === 0).forEach(element => result.push(element * 2));
const result = elements.filter(element => element % 5 === 0).map(element => element * 2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
for of loop | |
forEach | |
map |
Test name | Executions per second |
---|---|
for loop | 2835551.0 Ops/sec |
for of loop | 6612008.0 Ops/sec |
forEach | 5186379.5 Ops/sec |
map | 4636601.5 Ops/sec |
The benchmark focuses on the performance of different approaches to processing arrays in JavaScript. Specifically, it compares four methods for iterating over an array of randomly generated integers and filtering and transforming its elements based on a specific condition (in this case, whether the integer is divisible by 5).
For Loop
const result = [];
for (let i = 0; i < elements.length; i++) {
if (elements[i] % 5 === 0) {
result.push(elements[i] * 2);
}
}
For-of Loop
const result = [];
for (let element of elements) {
if (element % 5 === 0) {
result.push(element * 2);
}
}
for..of
syntax introduced in ES6, which iterates over the elements directly rather than their indices.ForEach Method
const result = [];
elements.filter(element => element % 5 === 0).forEach(element => result.push(element * 2));
filter
method with forEach
. It first creates a new array containing elements equal to or greater than zero, then applies a function to each element, pushing the modified values to the result array.Map Method
const result = elements.filter(element => element % 5 === 0).map(element => element * 2);
filter
to create an array of valid elements and then applies the map
method to transform these elements.forEach
, it also generates intermediate arrays.The benchmark results show the throughput (executions per second) for each method on a specific setup (Opera 116 on macOS):
map
or forEach
.Other alternatives that could be explored include:
for-of
syntax.This benchmark has highlighted the trade-offs between various JavaScript iteration methods when processing arrays, providing meaningful insights for developers when making decisions on which approach to implement in their codebases.