var array = new Array(100);
var alen = array.length;
for (var i = 0; i < array.length; i++) {
array[i];
}
array.forEach(function(i) {
array[i];
});
for (var i of array) {
array[i];
}
for (var i = 0, len = array.length; i < len; i++) {
array[i];
}
for (var i = 0; i < alen; i++) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for..of | |
for with cached length | |
for with pre-cached length |
Test name | Executions per second |
---|---|
for | 137734.2 Ops/sec |
foreach | 3856055.0 Ops/sec |
for..of | 237223.7 Ops/sec |
for with cached length | 275653.2 Ops/sec |
for with pre-cached length | 138767.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition
The provided JSON represents a benchmark test that compares the performance of different loop constructs in JavaScript: for
, foreach
, and variations thereof (for with cached length
and for..of
). The goal is to determine which approach yields the fastest execution time.
Loop Constructs Compared
for
loop: This is the most basic type of loop, where you increment a counter variable (i
) manually.foreach
loop: This loop iterates over an array using a callback function that receives the current element as an argument.for..of
loop: Introduced in ECMAScript 2015 (ES6), this loop is designed to iterate over arrays and other iterable objects, providing a more concise syntax than traditional for
loops.for with cached length
: In this variation, the array's length is stored in a separate variable (alen
) and used to increment the counter (i
). This approach avoids the overhead of repeatedly accessing array.length
.for with pre-cached length
: Similar to the previous point, but the loop increments i
using the cached value of alen
.Pros and Cons
for
loop: Lightweight, easy to understand, and supports various iterations (e.g., while
, do-while
). However, manual counter management can lead to errors.foreach
loop: Provides a concise syntax for iterating over arrays. It's often more readable than traditional for
loops but may have performance overhead due to callback function creation.for..of
loop: Offers a modern, expressive syntax that eliminates the need to manually increment a counter. However, it might not be supported in older browsers or Node.js versions.Library and Special Features
None mentioned in this specific benchmark definition.
Special JS Features or Syntax
The for..of
loop was introduced as a new iteration mechanism in ES6 (2015), providing an elegant way to iterate over arrays without manually incrementing counters. This syntax is more modern, readable, and efficient than traditional for
loops for many cases.
Alternatives
Other alternatives to these loop constructs include:
while
keyword to create a loop that continues as long as a condition is true.