var array = Array.from({length: 100});
var t;
for (let i = 0; i < array.length; i++) {
t = array[i];
}
array.forEach(function(v, i) {
t = v;
});
for (var v of array) {
t = v;
}
for (var [i, v] of array.entries()) {
t = v;
}
for (var k in array) {
t = array[k];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for..of | |
for..of over entries | |
for..in |
Test name | Executions per second |
---|---|
for | 28145284.0 Ops/sec |
foreach | 14462594.0 Ops/sec |
for..of | 10457642.0 Ops/sec |
for..of over entries | 1161500.4 Ops/sec |
for..in | 1201672.1 Ops/sec |
Let's break down what is being tested and compared here.
What is being tested?
The benchmark is testing the performance of different ways to iterate over an array in JavaScript: for
, forEach
, for...of
, for...of
over entries
, and for...in
.
What options are compared?
Here are the five test cases:
for
: A traditional for
loop with a counter variable i
.forEach
: Using the Array.prototype.forEach()
method to iterate over the array.for...of
: Using a for...of
loop to iterate directly over the array values.for...of
over entries: Using a for...of
loop to iterate over the key-value pairs of an array using entries()
.for...in
: Using a for...in
loop to iterate over the property names ( indices ) of an object, but here we are using it on an array.Pros and Cons:
Here's a brief summary:
for
: Pros: simple, familiar syntax; Cons: requires indexing variable.forEach
: Pros: concise syntax for iterating over arrays; Cons: may not be suitable for large datasets or performance-critical code.for...of
: Pros: concise and expressive syntax; Cons: may not work with older browsers (e.g., IE).for...of
over entries: Pros: allows iteration over both key-value pairs and array indices; Cons: requires modern JavaScript features (entries()
method).for...in
: Note that using for...in
on an array is generally discouraged, as it iterates over the property names (indices) rather than the actual values. This can lead to unexpected behavior if the array has non-index properties.Library usage:
None of these test cases use a specific library. The only external function used is Array.from()
in the script preparation code.
Special JS features or syntax:
for...of
: This loop syntax was introduced in ECMAScript 2015 (ES6).entries()
method: This method returns an array iterator that yields key-value pairs for each entry in an object. It was also introduced in ES6.Other alternatives:
For iterating over arrays, you can also use:
map()
or filter()
methods (if you need to transform or filter the data)for
loops) when performance is not a concernreduce()
, every()
, and some()
(when applicable)Please note that this answer provides a general overview, and the best approach will depend on the specific use case and requirements.