DEV Community

Discussion on: Let's loop - for...in vs for...of

Collapse
 
jamesthomson profile image
James Thomson

Totally unrelated to your article, which is a great write up of these for loops btw, but I always appreciate little optimisations so I hope you don't mind :)

It would be more performant to create a reference to Object.entries especially when referencing in a loop. As it stands the method will run on each loop which means not only is it running a method to return the entries which is costly, but also allocating memory. Not so bad for small object such as in your example, but large objects may show signs of degradation.

let obj = {a:1, b:2, c:3}
let entries = Object.entries(obj)
let newObj = {}
for (let idx in entries){
    const [key, value] = entries[idx]
    newObj[key] = value
}
Collapse
 
laurieontech profile image
Laurie

Definitely!