简体   繁体   English

hashtable如何确保将对象键散列到JavaScript中的唯一索引中

[英]How hashtable makes sure object keys are hashed into a unique index in JavaScript

After looking at a simple hash table implementation in JavaScript, the key index is computed as: 在JavaScript中查看简单的哈希表实现之后,密钥索引计算如下:

function index(str, max) {
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    var letter = str[i];
    hash = (hash << 5) + letter.charCodeAt(0);
    hash = (hash & hash) % max;
  }
  return hash;
}

So I'm wondering in the case of v8, how it uses a function similar to that but makes sure the index is unique on the object. 所以我想知道在v8的情况下,它是如何使用类似的函数,但确保索引在对象上是唯一的。 So if you do this: 所以,如果你这样做:

{ a: 'foo', b: 'bar' }

Then it becomes something like: 然后它变成类似于:

var i = index('a', 100000)
// 97
var j = index('b', 100000)
// 98

But if you have 100's or 1000's or more keys on an object, it seems like there might be collisions. 但是如果对象上有100或1000或更多的键,则可能会发生冲突。

Wondering how a hashtable guarantees they are unique, using v8 as a practical example. 想知道哈希表如何保证它们是唯一的,使用v8作为一个实际的例子。

V8 developer here. V8开发人员在这里。 Hashes of strings are not unique (that's kind of the point of using a hash function); 字符串的散列不是唯一的(这是使用散列函数的一种方式); V8 uses quadratic probing to deal with collisions (see source ). V8使用二次探测来处理冲突(参见来源 )。 You can read more about various strategies at https://en.wikipedia.org/wiki/Hash_table#Collision_resolution . 您可以在https://en.wikipedia.org/wiki/Hash_table#Collision_resolution上阅读有关各种策略的更多信息。

Also, hash = (hash & hash) % max; 另外, hash = (hash & hash) % max; is pretty silly ;-) 很傻;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM