var as = [];
for (var i = 0; i < 10000; i++) {
as.push(Math.floor(Math.random() * 1000));
}
const res = [];
for(const a of as.entries()) res.push(a);
const res = [];
for(let i = 0; i < as.length; i++) {
const a = as[i];
res.push(a);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.entries | |
Array for i |
Test name | Executions per second |
---|---|
Array.entries | 22995.7 Ops/sec |
Array for i | 1489.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Purpose
The benchmark is designed to compare two approaches for accessing elements in an array: using the entries()
method versus a traditional for
loop with indexing (i
).
Options Compared
Two options are compared:
entries()
method, which returns an iterator object that yields pairs of values - the key (index) and the value (array element) - for each element in the array.for
loop with indexing (i
): This option uses a traditional for
loop to iterate over the array elements, where i
is the index of the current element.Pros and Cons
Here are some pros and cons of each approach:
entries()
method (although most modern ones do)for
loop with indexing (i
):for
loop syntaxLibrary/Additional Features
There is no external library used in this benchmark. However, some modern JavaScript engines may have additional features or optimizations that affect performance.
Special JS Feature/Syntax
No special JavaScript feature or syntax is used in these test cases. Both approaches are standard and widely supported.
Alternatives
Other alternatives to compare in a similar benchmark might include:
forEach()
method instead of traditional for
loopmap()
function instead of indexing and pushing elements to an arrayreduce()
function instead of traditional accumulation (e.g., summing or accumulating values)Keep in mind that the choice of approach depends on the specific use case, performance requirements, and personal preference.