JavaScript Objects as Hashes? Is the complexity greater than O(1)?

前端 未结 2 1529
醉酒成梦
醉酒成梦 2020-11-27 12:48

For some algorithm I was writing recently I thought that a hash would be excellent. I thought that I could probably just use the member variables in an object as key value p

相关标签:
2条回答
  • 2020-11-27 13:30

    JavaScript objects are hashes. I cannot imagine any sane implementation that would not provide constant-time CRUD operations on object properties.

    Are you seeing specific performance issues with this approach?

    0 讨论(0)
  • 2020-11-27 13:40

    Yes they are hashes. The implementation is different across browsers. Despite many articles that would claim that objects are not hashes they very much behave like hashes, and therefore could be used as such.

    I had to prove this by running performance tests:

    The way to read these tests is if there is no performance difference in ops/sec when the size of object grows then that means objects are hashes. The defining characteristic of a hash is that the complexity of each operation is O(1) regardless of it being faster or slower in comparison to other operations.

    Tests:
    http://jsperf.com/objectsashashes/2 (100 keys)
    http://jsperf.com/objectsashashes/3 (100k keys)
    http://jsperf.com/objectsashashes/ (1 million keys)
    http://jsperf.com/objects-as-hashes-300-mil (10m keys)

    Note: Each browser is faster/slower at different operations. This seems to change between releases and year to year.

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