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 = [
["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],
];
let total = 0;
for(const item of array){
total += item[1];
}
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 | 8235080.5 Ops/sec |
Map for-of | 3917427.2 Ops/sec |
Let's dive into the explanation of what's being tested on this benchmark.
The provided JSON represents two test cases that compare the performance of iterating over an array using for...of
and Map.for...of
. Both approaches are designed to iterate over the same data, but they differ in how they access the elements.
Array for-of
In this approach, we have a nested array [["a", 1], ["b", 2], ...]
. The for...of
loop iterates over each inner array and assigns it to a constant item
. Then, inside the loop, we access the second element of the array (item[1]
) using indexing.
Map for-of
In this approach, we have a Map
object created from an object using Object.entries()
. The for...of
loop iterates over each key-value pair in the map and assigns it to a constant [key, value]
. Then, inside the loop, we access the second element of the array (value
) using indexing.
Now, let's discuss the pros and cons of each approach:
Array for-of
Pros:
Cons:
item[1]
) which can lead to errors if not used carefully.Map for-of
Pros:
Cons:
for...of
on objects.for...of
.Other considerations:
The alternative to using for...of
on arrays or maps is to use traditional indexing (array[i]
or map[key]
) instead. This approach can be faster for small arrays but may lead to errors and less readability.
As an example of special JS feature, note that the Object.entries()
method returns an array-like object containing a key-value pair as an array with two elements: [key, value]
.