Let's say I have a map with the keys:
const map = new Map([['a', 'Apple'], ['b', 'Banana']])
I want to loop through the keys of the map ('a'
, 'b'
).
I know these ways of looping through the keys:
Map.prototype.forEach()
map.forEach((_value, key) => {
console.log(key)
})
Pros: Simple
Cons: Have to ignore first param in function - (_value, key) =>
instead of just key =>
.
Map.prototype.keys()
and then Array.prototype.forEach()
[...map.keys()].forEach(key => {
console.log(key)
})
Pros: Callback can just be key =>
Cons: [...map.keys()]
. Might be confusing when reading the code and might be less performant.
for of
loop through Map.prototype[Symbol.iterator]()
for (const [key] of map) console.log(key)
Pros: Probably fast. Easy to read.
Cons: Not an arrow function (opinion that forEach is better).
for of
loop through Map.prototype.keys()
for (const key of map.keys()) console.log(key)
Very similar to previous method.
So I want to know which way is the most performant.
JSBench with the methods as per the following. These are the results from fastest to slowest:
Map.prototype.forEach()
for of
loop through Map.prototype.keys()
for of
loop through Map.prototype[Symbol.iterator]()
Map.prototype.keys()
and then Array.prototype.forEach()