var obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 7,
h: 8,
i: 9,
j: 10,
k: 11,
l: 12,
m: 13,
n: 14,
o: 15,
p: 16,
q: 17,
r: 18,
s: 19,
t: 20,
u: 21,
v: 22,
w: 23,
x: 24,
y: 25,
z: 26
};
var map = new Map(Object.entries(obj));
var array = [
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9],
[10],
[11],
[12],
[13],
[14],
[15],
[16],
[17],
[18],
[19],
[20],
[21],
[22],
[23],
[24],
[25],
[26],
];
let total = 0;
for(const item of array){
total += item[0];
}
let total = 0;
for (const [key, value] of map) {
total += value;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array for-of | |
Map for-of |
Test name | Executions per second |
---|---|
Array for-of | 4340558.0 Ops/sec |
Map for-of | 1036405.1 Ops/sec |
I'll break down what's being tested in this benchmark, compare the different approaches, and discuss their pros and cons.
Benchmark Definition:
The benchmark is comparing two ways to iterate over an array using the for...of
loop:
for...of
loop.Map
object created from the 2D array's entries.Benchmark Preparation Code:
The script creates a large 2D array and a corresponding Map
object from its entries. The array has 26 rows, each containing an array of numbers.
var obj = {
// ...
};
var map = new Map(Object.entries(obj));
Individual Test Cases:
There are two test cases:
for...of
loop.let total = 0;
for (const item of array) {
total += item[0];
}
Map
object created from the 2D array's entries.let total = 0;
for (const [key, value] of map) {
total += value;
}
Comparison:
The two approaches differ in how they iterate over the data:
Map
object, where each key is an index and the value is an array of numbers.Pros and Cons:
Map
object.for...of
loop handles the iteration internally.Map
object and iterating over its key-value pairs.Other Considerations:
Map
object from a large 2D array can consume significant memory. This might impact performance in scenarios where memory is limited.for...of
loop has been supported by most modern browsers for several years. However, older browsers may not support it.Alternatives:
For this specific benchmark, the alternatives are:
forEach
loop: Instead of using for...of
, you could use the forEach
method to iterate over each inner array in the 2D array.array.forEach((row) => {
total += row[0];
});
for...of
loop.Keep in mind that these alternatives may have different performance characteristics and may not be suitable for all use cases.