ES6 Maps and Sets: how are object keys indexed efficiently?

后端 未结 1 1488
攒了一身酷
攒了一身酷 2021-01-21 13:24

In ES6, Maps and Sets can use Objects as keys. However since the ES6 specification does not dictate the underlying implementation of these datastructures, I was wondering how do

相关标签:
1条回答
  • 2021-01-21 14:12

    Yes, the implementation is based on hashing, and has (amortized) constant access times.

    "they use object identity" is a simplification; the full story is that ES Maps and Sets use the SameValueZero algorithm for determining equality.

    In line with this specification, V8's implementation computes "real" hashes for strings and numbers, and chooses a random number as "hash" for objects, which it stores as a private (hidden) property on these objects for later accesses. (That's not quite ideal and might change in the future, but for now that's what it is.)

    Using memoryAddress % keySpace cannot work because the garbage collector moves objects around, and rehashing all Maps and Sets every time any object might have moved would be prohibitively complicated and expensive.

    0 讨论(0)
提交回复
热议问题