var myArraySmall = Array(3);
for (let i=0; i<3; i++) {
myArraySmall[i] = i;
}
for (ele of myArraySmall) {
let something = ele;
}
for (const ele of myArraySmall) {
let something = ele;
}
myArraySmall.forEach(function(s) {
let something = s;
});
for (let i=0; i<3; i++) {
let something = myArraySmall[i];
}
myArraySmall.map((i) => {
let something = i;
});
myArraySmall.forEach(s => {
let something = s;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for element of SMALL | |
for const element of SMALL | |
myArr forEach SMALL | |
array index SMALL | |
map | |
forEach ES6 SMALL |
Test name | Executions per second |
---|---|
for element of SMALL | 7568435.5 Ops/sec |
for const element of SMALL | 15427500.0 Ops/sec |
myArr forEach SMALL | 50719700.0 Ops/sec |
array index SMALL | 35450744.0 Ops/sec |
map | 18077240.0 Ops/sec |
forEach ES6 SMALL | 52956176.0 Ops/sec |
This benchmark on MeasureThat.net compares different ways to iterate over a small array (myArraySmall
containing 3 elements) in JavaScript. Let's break down each test case:
Test Case Options:
for (ele of myArraySmall)
: This uses the modern for...of
loop, designed specifically for iterating over iterable objects like arrays. It's concise and often the most readable option.
for (const ele of myArraySmall)
: Similar to the above but explicitly declares each element as const
, promoting immutability. This can be beneficial for clarity and preventing accidental reassignments within the loop.
myArraySmall.forEach(function(s) { ... })
: This uses the .forEach()
array method, which executes a provided function for each element in the array. It's functional in style and may be preferred if you need to perform side effects or modify elements within the loop.
for (let i=0; i<3; i++) { ... }
: This classic for
loop uses an index (i
) to access each element of the array directly using myArraySmall[i]
. While functional, it can be less readable than the other options for iterating over arrays.
myArraySmall.map((i) => { ... })
: The .map()
method creates a new array by applying a function to each element of the original array. While similar in concept to forEach
, it returns a transformed array as its output.
myArraySmall.forEach(s => { ... })
: This is essentially the same as the .forEach()
using a traditional function, but utilizes arrow functions (=>
) for a more concise syntax introduced in ES6 (ECMAScript 2015).
Pros and Cons:
for...of
and for const...of
:
.forEach()
:
map
).for
loop with index:
.map()
:
Alternatives:
While these tests focus on basic iteration, other techniques exist for working with arrays:
filter()
: Creates a new array containing only elements that pass a condition.reduce()
: Applies a function cumulatively to each element of an array, returning a single value.Let me know if you have any more questions about these test cases or JavaScript array manipulation in general!