在JavaScript中,Object.keys()。forEach()的内存效率比简单的for ... in循环要少吗? [英] In JavaScript is Object.keys().forEach() less memory efficient than a simple for...in loop?

查看:142
本文介绍了在JavaScript中,Object.keys()。forEach()的内存效率比简单的for ... in循环要少吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,你有一个非常大的JS对象,包含数百万个键/值对,你需要迭代它们。

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

此jsPerf示例显示了执行此操作的主要方法,并概述了速度差异。

This jsPerf example shows the main ways to do it, and outlines the speed differences.

我不知道的是:使用 Object.keys()与其他内存相比会对内存产生不同的影响循环方法,因为它需要创建首先包含所有对象键的索引数组?

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?

推荐答案

您正在寻找的是对对象或数组属性的延迟迭代。这在ES5中是不可能的(因此在许多实现中不可能,例如node.js)。我们最终会得到这个。

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.

内存方面,中的 Object.keys.forEach 将整个属性集加载到内存中。每个JS引擎使用多少实际内存可能会有很大差异。您应该始终在不同的场景下测试您的代码,并使用多个引擎来确定哪种方法最适合您的应用程序。

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.

这篇关于在JavaScript中,Object.keys()。forEach()的内存效率比简单的for ... in循环要少吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆