gpt4 book ai didi

javascript - 关联数组是否像哈希表一样执行?

转载 作者:数据小太阳 更新时间:2023-10-29 05:15:57 25 4
gpt4 key购买 nike

想象一下,您在 JavaScript 中有一个关联数组:

var hashTable = {};

hashTable["red"] = "ff0000";
hashTable["green"] = "00ff00";
hashTable["blue"] = "0000ff";

当您检索这样的值时会发生什么:

var blue = hashTable["blue"];

性能是否与其他语言的哈希表相似?我的意思是,是否存在用于确定属性位置的实际哈希函数,或者是否存在循环搜索,例如:

for (var color in hashTable) {
if (hashTable.hasOwnProperty(color)) {
//look for matching key
}
}

实现是否因浏览器而异?我找不到与此特定主题相关的任何内容。谢谢。

最佳答案

它在不同的 javascript 引擎中以不同的方式实现,如今,对象似乎不再由“类似字典”的数据结构支持。

来自 https://developers.google.com/v8/design :

JavaScript is a dynamic programming language: properties can be added to, and deleted from, objects on the fly. This means an object's properties are likely to change. 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. This basic idea is not new - the prototype-based programming language Self used maps to do something similar. In V8, an object changes its hidden class when a new property is added.

Firefox 的 IonMonkey 做类似的事情。来自对 Mozilla 开发人员的采访 ( http://www.infoq.com/news/2011/05/ionmonkey ):

Dynamic languages probably don't have any inherent optimization advantages, but they do have interesting optimizations that static languages don't. For example, when you're writing JavaScript, objects appear to the user as hash tables, mapping property names to values. If they were actually implemented like that, they would be slow and use a lot of memory.

A good engine is able to internally group objects that look the same, sort of extracting an internal Java-like class out of them. The JIT can then treat the object as having an actual type, generating super fast code that avoids an expensive property lookup.

关于javascript - 关联数组是否像哈希表一样执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16825540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com