Pensierinmusica
Pensierinmusica

Reputation: 6950

In JavaScript is Object.keys().forEach() less memory efficient than a simple for...in 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 main ways to do it, and outlines the speed differences.

What I wonder though is: using Object.keys() would have a different impact on memory compared to the other looping methods, since it needs to create the "index" array that contains all the object keys first?

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

Upvotes: 3

Views: 3483

Answers (2)

imelgrat
imelgrat

Reputation: 2577

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

Memory-wise, both for ... in and Object.keys.forEach will load the whole set of attributes to memory. How much actual memory is used in each JS engine can vary significantly. You should always test your code on different scenarios and using several engines to determine which works best on your application.

Upvotes: 3

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

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

for-in vs Object.key forEach without inherited properties

Upvotes: 0

Related Questions