var object = {};
for (let i = 1; i <= 100000; i++) object[String(i)] = i;
for (let entries = Object.entries(object), i = -1, length = entries.length; ++i < length;) {
const t = entries[i];
window.k = t[0]
window.v = t[1];
}
const entries = Object.entries(object);
entries.forEach(([k, v]) => {
window.k = k;
window.v = v;
});
const entries = Object.entries(object);
for (const [k, v] of entries) {
window.k = k;
window.v = v;
}
for (let entries = Object.entries(object), i = -1, t; t = entries[++i]; i) {
window.k = t[0];
window.v = t[1];
}
for (let entries = Object.entries(object), i = -1; ++i in entries;) {
const t = entries[i];
window.k = t[0];
window.v = t[1];
}
for (const k in object) {
window.k = k;
window.v = object[k];
}
const entries = Object.entries(object)
entries.reduce((_, [k, v]) => {
window.k = k;
window.v = v;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for i < length | |
.forEach(t) | |
for..of | |
for t = array[i] | |
for i=0; i in array | |
for i in array, | |
.reduce |
Test name | Executions per second |
---|---|
for i < length | 252.9 Ops/sec |
.forEach(t) | 247.6 Ops/sec |
for..of | 251.3 Ops/sec |
for t = array[i] | 251.0 Ops/sec |
for i=0; i in array | 257.2 Ops/sec |
for i in array, | 374.1 Ops/sec |
.reduce | 234.5 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance of different loop constructs in JavaScript: for
loops, array methods (.forEach
, .for...of
, and .reduce
). The goal is to determine which approach is the most efficient.
Loop Constructs Compared
for i = 0; ++i in object
: This construct uses the "in" operator to iterate over the properties of an object.for i < length
: A traditional for
loop that increments a counter until it reaches the end of an array or object.for t = entries[++i]
: A variation of the traditional for
loop, where the value of t
is assigned using the post-increment operator (++i
)..forEach(t)
: An array method that executes a callback function once for each element in an array..for...of
: An array method that iterates over an array using a for...of
loop..reduce((_, [k, v]) => { ... })
: An array method that applies a reduction function to each element in an array.Pros and Cons of Each Approach
for i = 0; ++i in object
:for i < length
:for
loop is easy to understand and optimize.for t = entries[++i]
:for
loop, but with a concise syntax..forEach(t)
:.for...of
:.reduce((_, [k, v]) => { ... })
:Library Used
The Object.entries()
method is used in several test cases. This method returns an array of key-value pairs for each property in the object.
Browsers and JavaScript Versions Used
The benchmark appears to be run on Firefox 94 with modern JavaScript features enabled.
In summary, the results suggest that the most efficient loop construct is the traditional for
loop (for i < length
), followed closely by the .for...of
method. The other methods are less efficient, but still usable in certain situations.