Is Set a hashed collection in JavaScript?

北城以北 提交于 2019-12-11 04:21:14

问题


I was asking myself this question. Is Set a hashed collection in JavaScript?

For example, Set.prototype.has will iterate the entire Set or do its implementations use an internal hash table to locate an item within the collection?


回答1:


The ECMAScript 2015 specification says that:

Set objects must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection.

Obviously they can't force a particular JS engine to actually do that, but in practice JS engines will do the right thing.




回答2:


The ES6 specification does not require a specific implementation, but it does indicate that it should be better than O(n) (so better than a linear lookup). And, since the purpose of the Set object is to be efficient at looking up items in the Set, it most surely uses some sort of efficient lookup system like a hash.

If you want to know for sure how it works, you'd have to look at the open source code for the Firefox or Chrome implementations.

You could also benchmark it to prove that the lookup speed is not O(n), but something more efficient than that.



来源:https://stackoverflow.com/questions/39763008/is-set-a-hashed-collection-in-javascript

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