var arr = [];
for (let i = 0; i < 1000; i++) {
arr[i] = i;
}
function foo(bar) {
return bar;
}
for (let i = 0, len = arr.length; i < len; i++) {
foo(arr[i]);
}
for (let i in arr) {
foo(arr[i]);
}
for (let val of arr) {
foo(val);
}
arr.forEach(function(val) {
foo(val);
});
arr.map(function(val) {
return foo(val);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for in | |
for of | |
forEach | |
map |
Test name | Executions per second |
---|---|
for | 7955.5 Ops/sec |
for in | 5500.5 Ops/sec |
for of | 14047.0 Ops/sec |
forEach | 15700.6 Ops/sec |
map | 14739.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark measures the performance of different JavaScript loops for iterating over an array:
for
loopfor in
loop (which is deprecated)for of
loop (introduced in ECMAScript 2015)forEach
methodmap
methodOptions Compared
The five options are compared to determine which one is the fastest for iterating over an array.
Here's a brief overview of each option:
for
loop: This is the traditional way of looping over an array in JavaScript. It uses a manual index variable (i
) and checks the bounds of the array.for in
loop: This option is deprecated and should not be used for iterating over arrays. It iterates over the properties (keys) of the object, not its values.for of
loop: Introduced in ECMAScript 2015, this loop is designed specifically for iterating over iterable objects like arrays.forEach
method: This is a built-in method on arrays that allows you to execute a callback function for each element in the array.map
method: Another built-in method on arrays, map
returns a new array with the results of applying a provided function to each element in the original array.Library and Special JS Features
None of the test cases use any external libraries or special JavaScript features. They only rely on built-in JavaScript functionality.
Other Alternatives
If you're looking for alternative ways to iterate over arrays, some options include:
reduce()
methodevery()
and some()
methodsKeep in mind that the performance of these alternatives may vary depending on the specific use case and JavaScript engine.
Benchmark Preparation Code
The provided benchmark preparation code sets up an array with 1000 elements, each initialized to its index value. It also defines a simple foo
function that takes a single argument and returns it.
Individual Test Cases
Each test case has a unique benchmark definition that represents the specific loop being tested. The Test Name
field provides a clear indication of which loop is being measured.