var array = new Array(100);
for (var i = 0; i < array.length; i++) {
array[i] = i * 10000
}
for (let i = 0; i < array.length; i++) {
array[i];
}
array.forEach((i) => {
array[i];
});
for (let i = 0, length = array.length; i < length; i++) {
array[i];
}
for (var i of array) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for (cached length) | |
for..of |
Test name | Executions per second |
---|---|
for | 134827.9 Ops/sec |
foreach | 163452.4 Ops/sec |
for (cached length) | 308336.5 Ops/sec |
for..of | 302345.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of four different loop constructs in JavaScript:
for
loops with and without caching the array length.foreach
loops, which are a part of the ECMAScript standard.The benchmark aims to measure the execution speed of each loop construct for an array of 100 elements.
Loop Constructs
Here's a brief explanation of each loop construct:
for
loopfor (var i = 0; i < array.length; i++) {
array[i];
}
This is the most basic type of loop in JavaScript, where we increment a counter variable (i
) to iterate over the array elements.
Pros and Cons:
foreach
loop (ECMAScript standard)array.forEach((i) => {
array[i];
});
This is a newer, more concise way of iterating over arrays in JavaScript. The forEach
method executes a callback function once for each element in the array.
Pros and Cons:
for
loops.for
loop with cached lengthfor (var i = 0, length = array.length; i < length; i++) {
array[i];
}
This variant precomputes the array length and stores it in a variable (length
). This way, we avoid having to access array.length
on each iteration.
Pros and Cons:
for
loops due to reduced index lookups.array.length
repeatedly.for..of
loop (ECMAScript standard)for (var i of array) {
array[i];
}
This is a newer, more concise way of iterating over arrays in JavaScript. The for...of
loop executes an expression (in this case, the expression that yields each element) for each iteration.
Pros and Cons:
for
loops.Library Usage
None of the provided loop constructs rely on any external libraries. However, if you were to use other libraries or frameworks for your benchmarking code, you would need to consider their potential impact on performance and overall results.
Special JavaScript Features
The foreach
loop and for...of
loop utilize special ECMAScript features: the forEach
method (ECMAScript standard) and the for...of
loop (ECMAScript standard), respectively. These features are designed to make array iteration more concise and expressive, but might not be supported in older browsers or platforms.
Alternative Loop Constructs
There are other loop constructs available in JavaScript, such as:
while
loops: suitable for simple iterations with manual index management.map()
, filter()
, and reduce()
: designed for more complex array operations and transformations.