JavaScript has Object.keys (). ForEach () less memory than simple for ... in a loop?

Imagine you have a very large JS object containing millions of key / value pairs, and you need to iterate over them.

This jsPerf example shows the basic ways to execute it and describes the differences in speed.

It is interesting, however, that using Object.keys() will have a different memory effect compared to other loop methods, since first you need to create an "index" array that contains all the keys of the objects?

Are there any optimizations in the source code that prevent this?

+2
source share
2 answers

What you are looking for is a lazy iteration over the properties of an object or array. This is not possible in ES5 (thus, it is not possible in many implementations such as node.js). We will get it in the end.

Memory, both for ... in and Object.keys.forEach , will load the entire set of attributes into memory. How much actual memory is used in each JS engine can vary significantly. You should always test your code in different scenarios and use several engines to determine which ones are best for your application.

+2
source

well, the problem is that Object Keys combine the for..in property with the hasOwn property, so depending on your final goal, they can be exclusive or interchangeable. since for the standard you saw them yourself, it all comes down to the implementation of the engine. check this answer for more info

for-in vs Object.key forEach without inherited properties

0
source

Source: https://habr.com/ru/post/1015296/


All Articles