var arr = new Array(1000000).fill(0)
arr.map(n => {});
const length = arr.length;
for (let i = 0; i < length; i++) {}
arr.forEach(n => {});
for (const num of arr) {}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map | |
forLoop | |
forEach | |
forOf |
Test name | Executions per second |
---|---|
Map | 109.7 Ops/sec |
forLoop | 4482.2 Ops/sec |
forEach | 584.7 Ops/sec |
forOf | 303.1 Ops/sec |
Let's break down the provided benchmark test cases.
What is being tested?
The benchmark tests various JavaScript loop constructs: map
, for
loops (with and without const num of arr
syntax), and forEach
. The goal is to compare the performance of these different loop approaches on a large array (arr
) with 1 million elements, initialized with zeros.
Options being compared
The test cases compare:
map()
method to create a new array by applying a transformation function to each element.for
loop with an index variable (i
) to iterate through the array.for...of
loop, which is a newer syntax that iterates over arrays without requiring an explicit index variable.forEach()
method to execute a function on each element of the array.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
i
.Library usage
None of the provided test cases explicitly use any external libraries, although forEach()
method is an internal API in modern JavaScript.
Special JS features or syntax
The only special feature used in this benchmark is the New For Loop Syntax (for...of
), which was introduced in ECMAScript 2015 (ES6). This syntax allows iterating over arrays without requiring an explicit index variable.
Other alternatives
If you wanted to test alternative loop constructs, consider adding additional test cases for:
reduce()
filter()
some()
and every()
Keep in mind that these alternatives would require significant changes to the benchmark script and might not provide meaningful comparisons with the original tests.