In JavaScript is Object.keys().forEach() less memo

2019-05-15 05:23发布

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?

2条回答
爷的心禁止访问
2楼-- · 2019-05-15 06:01

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

查看更多
我命由我不由天
3楼-- · 2019-05-15 06:13

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.

查看更多
登录 后发表回答