我刚刚读到这个问题:are there dictionaries in javascript like python?
其中一个答案说你可以像 Python 字典一样使用 JavaScript 对象。真的吗?对象中的键查找的性能如何?是O(1)吗?向对象添加键也是恒定时间(散列)吗?
最佳答案
V8 design docs意味着查找至少会这么快,甚至更快:
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.
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.
不过,由于隐藏类的创建,听起来添加新键可能会稍微慢一些。
关于javascript - JavaScript 对象中键查找的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666564/