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

标签 javascript hashtable associative-array

想象一下,您在 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/

相关文章:

php - PHP通过xhr获取数据

javascript - 如何启动可以访问 node.js 中的局部变量的 REPL?

javascript - 链接原型(prototype)和原型(prototype)继承

javascript - JQuery 父选择器和淡出

java - java读取txt文件并将数据存储在哈希表中

python - Python 的哈希函数顺序背后的逻辑是什么?

javascript - 在 JavaScript 中添加有序哈希数据类型是否合理?

arrays - 如何使用数组作为值在 Pascal 中创建关联数组

php - 如何通过 URL 参数将 Javascript/jQuery 数组发送到 PHP?

php - 为什么我不能访问这个关联数组值?