var array = new Array(100);
var i = 0;
for (i; i < array.length; i++) {
console.log(i);
}
array.forEach(function(item, index) {
console.log(item);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 |
Test name | Executions per second |
---|---|
1 | 1544660.9 Ops/sec |
2 | 569581.7 Ops/sec |
I'll break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing two approaches for iterating over an array in JavaScript:
for
loopforEach()
method with callback functionScript Preparation Code
Before running each test, the script prepares by creating a new array of size 100 and declaring a variable i
initialized to 0.
var array = new Array(100);
var i = 0;
This code is executed before each iteration, ensuring consistent initial conditions for both tests.
Options Compared
The two options being compared are:
for
loop: Iterates over the array using a manual incrementing counter (i
).forEach()
method with callback function: Iterates over the array by invoking the callback function on each element.Pros and Cons of Each Approach:
for
loop:i
)forEach()
method with callback function:In general, the forEach()
method is a better choice when you need to iterate over an array without modifying it, and you want a lightweight, efficient solution. However, for manual incrementing counters or complex logic, the traditional for
loop might be more suitable.
Library Usage
There doesn't appear to be any external libraries used in this benchmark. The forEach()
method is a built-in JavaScript function.
Special JS Features/Syntax
This benchmark doesn't use any special JavaScript features or syntax beyond what's considered standard for 2022 (ES6+). If you're interested in exploring more advanced features, I can explain them later!
Other Alternatives
If you wanted to modify this benchmark to compare other iteration approaches, consider the following alternatives:
while
loop instead of the traditional for
loopArray.prototype.forEach()
with optional second argument ( callback function) or using map()
and reduce()
iterable-iteratee
library for more advanced iteration techniquesIf you have any further questions or would like to explore alternative approaches, feel free to ask!