var array = [1,2,3,4,5,6,7,8,9,10];
for (const element of array) {
console.log(element);
}
array.forEach(function (element) {
console.log(element);
});
for (let i = 0; i < array.length; ++i) {
console.log(array[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for ... of | |
Array.forEach | |
for cycle |
Test name | Executions per second |
---|---|
for ... of | 12247.7 Ops/sec |
Array.forEach | 11902.4 Ops/sec |
for cycle | 27965.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Description
The test compares three ways to iterate through an array in JavaScript: for...of
, Array.forEach
, and a traditional for
loop with an index variable (i
). The goal is to determine which approach is the fastest.
Options Compared
for...of
.Pros and Cons
for...of
Libraries Used
None explicitly mentioned in the benchmark definition. However, Array.forEach
uses the built-in JavaScript Array prototype.
Special JS Features or Syntax
for...of
requires a modern JavaScript environment (ES6+).Other Alternatives
For iterating through arrays, other options exist, such as:
In terms of benchmarking and performance comparison, MeasureThat.net is a unique tool that allows users to create and run JavaScript microbenchmarks.
Keep in mind that benchmark results can vary depending on specific use cases, hardware, and software environments. These explanations are intended to provide general insights into the options being compared.