const planes = new Array(1_000_000).fill(2);
for (const plane of planes) {
Math.sqrt(plane);
}
for (let i = 0; i < planes.length; i++) {
const plane = planes[i];
Math.sqrt(plane);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-of | |
for-index |
Test name | Executions per second |
---|---|
for-of | 144.7 Ops/sec |
for-index | 756.7 Ops/sec |
The provided benchmark is designed to compare the performance of two different loops in JavaScript: the for-of
loop and the traditional for
loop (also known as the indexed for
loop).
Name: for of vs for loops
Script Preparation Code:
const planes = new Array(1_000_000).fill(2);
This prepares an array named planes
with 1,000,000 elements, all of which are set to 2
. This setup allows both types of loops to iterate over a large data set, providing a meaningful comparison of their performance.
for-of Loop
for (const plane of planes) {
Math.sqrt(plane);
}
Indexed for Loop
for (let i = 0; i < planes.length; i++) {
const plane = planes[i];
Math.sqrt(plane);
}
The key metrics to analyze from the benchmark results are the "Executions Per Second" for both loops.
for-index
for-of
for-of
loop is executed approximately 171 times in one second.Pros:
Cons:
Pros:
Cons:
forEach Method
Array.prototype.forEach
can be an alternative to both loops. It's readable but generally slower than the traditional for
loop.planes.forEach(plane => Math.sqrt(plane));
map Method
Array.prototype.map
can be used. It creates a new array based on the return value from a provided function.const results = planes.map(plane => Math.sqrt(plane));
When choosing between these approaches, developers should consider both performance needs and code readability. The indexed loop may be preferred in performance-critical applications, while the for-of
loop offers cleaner syntax for scenarios where performance is less of a concern.
In more complex applications, understanding the context in which these loops are used (size of the dataset, readability, scope of variables, etc.) is vital to make the best choice tailored to specific needs.