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

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

问题描述

我刚刚看到这个问题:在javascript中有字典,如python?

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

其中一个答案说您可以使用JavaScript对象,如Python字典。真的吗?对象中的键查找的性能是什么?是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天全站免登陆