const items = Array.from({length: 500000}, () => Math.floor(Math.random() * 40));
let index = 0;
items.forEach(i => index++);
const items = Array.from({length: 500000}, () => Math.floor(Math.random() * 40));
let index = 0;
for (let i in items) {
item = items[i]
index++;
}
const items = Array.from({length: 500000}, () => Math.floor(Math.random() * 40));
let index = 0;
for (let i of items) {
index++;
}
const items = Array.from({length: 500000}, () => Math.floor(Math.random() * 40));
let index = 0;
for(let i = 0; i < items.length; ++i) {
item = items[i]
index++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for-in | |
for-of | |
for |
Test name | Executions per second |
---|---|
foreach | 6.5 Ops/sec |
for-in | 3.6 Ops/sec |
for-of | 7.1 Ops/sec |
for | 4.7 Ops/sec |
The benchmark titled "javascript loops2" focuses on testing and comparing the performance of different loop constructs in JavaScript. In particular, it measures the execution speed of four common iterating patterns when used with an array containing 500,000 randomly generated items. The loops tested and their comparisons are as follows:
forEach:
items.forEach(i => index++);
break
or return
.for-in:
for (let i in items) { item = items[i]; index++; }
for-of:
for (let i of items) { index++; }
for:
for(let i = 0; i < items.length; ++i) { item = items[i]; index++; }
From the benchmark results, the loop performance can be observed as follows:
Execution Speed: The traditional for
loop, while slightly slower in this benchmark, is often considered the go-to for performance-critical scenarios due to direct access to array elements. In many cases, optimizing JavaScript for performance requires careful consideration of the loop constructs.
Readability vs. Performance: There is often a trade-off between code readability and performance. While forEach
and for-of
offer a more modern and clutter-free approach, they might sacrifice execution speed.
Using Libraries: The benchmark does not utilize any external libraries, but developers sometimes turn to utility libraries like Lodash or Underscore.js for more complex operations on collections, which can offer enhanced functionality (e.g., chaining, immutability) but at the cost of additional overhead.
In conclusion, when choosing a loop type in JavaScript, developers should consider not only the performance characteristics as revealed by such benchmarks but also code clarity, maintainability, and the specific needs of their application.