var myArrayLarge = Array(10000);
for (let i=0; i<10000; i++) {
myArrayLarge[i] = i;
}
for (ele of myArrayLarge) {
let something = ele;
}
for (const ele of myArrayLarge) {
let something = ele;
}
myArrayLarge.forEach(function(s) {
let something = s;
});
for (let i=0; i<10000; i++) {
let something = myArrayLarge[i];
}
myArrayLarge.map((i) => {
let something = i;
});
myArrayLarge.forEach(s => {
let something = s;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for element of LARGE | |
for const element of LARGE | |
myArr forEach LARGE | |
array index LARGE | |
map LARGE | |
forEach ES6 LARGE |
Test name | Executions per second |
---|---|
for element of LARGE | 3413.1 Ops/sec |
for const element of LARGE | 10649.6 Ops/sec |
myArr forEach LARGE | 69630.7 Ops/sec |
array index LARGE | 14982.5 Ops/sec |
map LARGE | 6294.0 Ops/sec |
forEach ES6 LARGE | 69906.4 Ops/sec |
This benchmark tests the performance of different ways to iterate over a large array in JavaScript.
Options Compared:
for (ele of myArrayLarge)
(for element of LARGE
): This uses the modern for...of
loop, which iterates directly over elements in an iterable object like an array. It's concise and often considered more readable than other methods.for (const ele of myArrayLarge)
(for const element of LARGE
): Similar to the above but uses const
to declare each element variable. This enforces that the variable cannot be reassigned, which can improve code clarity and performance in some cases.myArrayLarge.forEach(function(s) { ... })
(myArr forEach LARGE
): Uses the .forEach()
array method, which takes a callback function to execute for each element in the array. This is a common pattern for simple operations on array elements.for (let i=0; i<10000; i++) { ... }
(array index LARGE
): A traditional for
loop that iterates using an index to access each element by its position in the array. This method can be less readable than the other options.myArrayLarge.map((i) => { ... })
(map LARGE
): Uses the .map()
array method, which creates a new array with the results of applying a provided function to each element in the original array.Pros and Cons:
for...of
and forEach
: Concise and readable, potentially performant.map
: Powerful for transforming arrays, but can be less efficient for simple iterations.for
loop with index: Can be explicit and allow fine-grained control over iteration, but often less readable and potentially slower than other methods.Other Considerations:
Library Usage: None of the test cases use libraries. The benchmark focuses on core JavaScript array iteration methods.
Alternatives:
Promise.all
or async iterators could be more efficient by processing elements in batches without blocking.Let me know if you have any more questions!