var items = new Array(1000000);
for (var index = 0, item = null; (item = items[index]); index++);
for (var index = 0; index < items.length; index++) {
var item = items[index];
}
items.forEach(item => {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for normal | |
foreach |
Test name | Executions per second |
---|---|
for | 6522789.0 Ops/sec |
for normal | 3.9 Ops/sec |
foreach | 248.3 Ops/sec |
Let's break down the provided benchmark data and explain what is being tested, compared, and considered.
Benchmark Definition JSON
The benchmark definition
json represents a single test case for measuring JavaScript performance. It contains three key elements:
var items = new Array(1000000);
) before running the benchmark.Individual Test Cases
There are three individual test cases:
for
for
loop to iterate over the array and retrieve an item at each index.for normal
for
loop that retrieves items from the array directly without assigning them to a variable.foreach
forEach()
method to iterate over the array and execute an anonymous callback function for each item.Library Usage
None of these test cases explicitly use any JavaScript libraries, but it's worth noting that some browser versions (like Chrome 80) might rely on internal libraries or engines to execute the JavaScript code.
Special JS Features/Syntax
for
loop with a variable declaration (var index = 0;
) is not specific to modern JavaScript and has been around since early versions of ECMAScript. It's still supported by most browsers.for
loop (items.forEach(item => {});
) is a feature introduced in ECMAScript 2015 (ES6) and is widely supported by modern browsers.Pros and Cons
Here's a brief summary of the pros and cons for each test case:
for
for normal
foreach
Other Alternatives
Some alternative approaches for iterating over arrays in JavaScript include:
Array.prototype.forEach()
: Similar to the foreach
test case, but with a more explicit function declaration (function(item) { }
).for...of
: Introduced in ECMAScript 2015 (ES6), this is another modern loop syntax that allows iterating over arrays.items[index]
) instead of relying on the array's length or forEach()
method.Please note that performance differences between these approaches can be small and may vary depending on specific browser versions, platform, and context.