var array = [0,1,2,3,4];
array.forEach((num) => {
console.log(num);
});
var array = [0,1,2,3,4];
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
};
var array = [0,1,2,3,4];
var i = 0;
while (i < array.length) {
console.log(array[i]);
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
each | |
for | |
while |
Test name | Executions per second |
---|---|
each | 4101.8 Ops/sec |
for | 4196.0 Ops/sec |
while | 2933.2 Ops/sec |
I'll explain the benchmark test and its different approaches.
Overview of the Benchmark
The benchmark tests three ways to loop through an array in JavaScript: forEach
, for
, and while
. The goal is to determine which approach is fastest.
Looping Approaches
There are three main looping approaches being tested:
forEach()
: This method calls a provided function once for each element in the array, with the current element as an argument. In this benchmark, it's used to log each element of the array
variable.for
loop: A traditional loop that uses a counter variable (i
) to iterate through the array. It checks the length of the array and increments the counter until it reaches the end.while
loop: A loop that continues as long as a certain condition is met (in this case, i < array.length
). The loop body executes each iteration.Pros and Cons
Here's a brief overview of each approach:
forEach()
:for
loop:array.length
) and is less intuitive for some developers.while
loop:Library Usage
None of the benchmark test cases use a library explicitly. However, it's worth noting that some JavaScript engines, like V8 (used by Chrome), have built-in optimizations and features that can affect performance in certain scenarios.
Special JS Features or Syntax
The benchmark does not use any special JavaScript features or syntax, such as async/await
, promises
, or modern array methods like map()
or filter()
. It only focuses on the basic looping approaches mentioned above.
Other Alternatives
If you're interested in exploring alternative ways to loop through arrays in JavaScript, here are a few examples:
reduce()
: A method that accumulates values in an array by applying a reduction function to each element.every()
, some()
, and forEach()
with Array.prototype.forEach.call()
: These methods can be used to iterate over arrays using a similar approach to for
loops.Overall, the benchmark provides a straightforward way to compare the performance of three common looping approaches in JavaScript, allowing developers to choose the most efficient method for their specific use case.