javascript关联数组使用什么样的散列函数/算法?

时间:2015-06-07 15:54:58

标签: javascript hashmap associative-array

我们了解到有许多不同的哈希算法/函数,我很好奇javascript使用哪一个(v8,如果实现很重要)。

1 个答案:

答案 0 :(得分:6)

由于V8是开源的,你可以去源:

这里是GetHash():https://github.com/v8/v8/blob/master/src/objects.cc#L903

而且,以下是不同类型的一些哈希函数:https://github.com/v8/v8-git-mirror/blob/bda7fb22465fc36d99b4053f0ef60cfaa8441209/src/utils.h#L347

而且,这看起来像字符串的核心哈希计算:https://code.google.com/p/v8/source/browse/trunk/src/objects.cc?spec=svn6&r=6#3574

uint32_t String::ComputeHashCode(unibrow::CharacterStream* buffer,
                                 int length) {
  // Large string (please note large strings cannot be an array index).
  if (length > kMaxMediumStringSize) return HashField(length, false);

  // Note: the Jenkins one-at-a-time hash function
  uint32_t hash = 0;
  while (buffer->has_more()) {
    uc32 r = buffer->GetNext();
    hash += r;
    hash += (hash << 10);
    hash ^= (hash >> 6);
  }
  hash += (hash << 3);
  hash ^= (hash >> 11);
  hash += (hash << 15);

  // Short string.
  if (length <= kMaxShortStringSize) {
    // Make hash value consistent with value returned from String::Hash.
    buffer->Rewind();
    uint32_t index;
    hash = HashField(hash, ComputeArrayIndex(buffer, &index, length));
    hash = (hash & 0x00FFFFFF) | (length << kShortLengthShift);
    return hash;
  }

  // Medium string (please note medium strings cannot be an array index).
  ASSERT(length <= kMaxMediumStringSize);
  // Make hash value consistent with value returned from String::Hash.
  hash = HashField(hash, false);
  hash = (hash & 0x0000FFFF) | (length << kMediumLengthShift);
  return hash;
}

值得一提的是V8尽可能避免在对象属性中使用哈希表,而是出于性能原因,将已知属性引用编译为直接索引引用而不是运行时哈希查找(虽然这有时是可能的 - 取决于代码。)