JavaScript 对象中键查找的性能 [英] Performance of key lookup in JavaScript object

查看:32
本文介绍了JavaScript 对象中键查找的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了这个问题:javascript 中是否有像 python 一样的字典?

I just read this question: are there dictionaries in javascript like python?

其中一个答案说你可以使用像 Python 字典这样的 JavaScript 对象.真的吗?在对象中进行键查找的性能如何?是 O(1) 吗?向对象添加键是否也是恒定时间(散列)?

One of the answers said that you can use JavaScript objects like Python dictionaries. Is that true? What is the performance of a key lookup in an object? Is it O(1)? Is adding a key to the object also constant time (hashing)?

推荐答案

V8 设计文档 意味着查找至少会这么快,如果不是更快的话:

The V8 design docs imply lookups will be at least this fast, if not faster:

大多数 JavaScript 引擎使用类似字典的数据结构作为对象属性的存储 - 每个属性访问都需要一个动态查找以解析属性在内存中的位置.这个方法使访问 JavaScript 中的属性通常很多比在编程语言中访问实例变量慢,比如Java 和 Smalltalk.在这些语言中,实例变量位于由于固定对象,由编译器确定的固定偏移量由对象的类定义的布局.访问只是一个问题内存加载或存储,通常只需要一条指令.

Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk. In these languages, instance variables are located at fixed offsets determined by the compiler due to the fixed object layout defined by the object's class. Access is simply a matter of a memory load or store, often requiring only a single instruction.

为了减少访问 JavaScript 属性所需的时间,V8 做了不要使用动态查找来访问属性.相反,V8 动态在幕后创建隐藏的类.[...] 在 V8 中,对象发生变化添加新属性时的隐藏类.

To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes. [...] In V8, an object changes its hidden class when a new property is added.

不过,由于隐藏类的创建,添加新密钥的速度可能会稍微慢一些.

It sounds like adding a new key might be slightly slower, though, due to the hidden class creation.

这篇关于JavaScript 对象中键查找的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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