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

好久不见. 提交于 2019-12-13 02:35:03

问题


After looking at a simple hash table implementation in JavaScript, the key index is computed as:

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. 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.

Wondering how a hashtable guarantees they are unique, using v8 as a practical example.


回答1:


V8 developer here. 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). You can read more about various strategies at https://en.wikipedia.org/wiki/Hash_table#Collision_resolution.

Also, hash = (hash & hash) % max; is pretty silly ;-)



来源:https://stackoverflow.com/questions/48046076/how-hashtable-makes-sure-object-keys-are-hashed-into-a-unique-index-in-javascrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!