In JavaScript is Object.keys().forEach() less memory efficient than a simple for…in loop?

空扰寡人 提交于 2020-01-02 06:51:41

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/28640729/in-javascript-is-object-keys-foreach-less-memory-efficient-than-a-simple-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!