Complexity of accessing data in an object

前端 未结 2 543
慢半拍i
慢半拍i 2021-01-02 05:03

In some of the projects I\'m working on as part of my day job, I need to access data in very large JS objects (on the order of thousands of key-value pairs). I\'m trying to

相关标签:
2条回答
  • 2021-01-02 05:48

    Javascript objects are actually Hashes, so the complexity is O(1) for all engines.

    obj.field is an alias for obj['field'], so they have the same performances.

    You can find some JS hashes performance tests here, unfortunately only for your browser engine.

    0 讨论(0)
  • 2021-01-02 06:02

    In the worst case the complexity of a JS object lookup is O(1), it's the complexity of a hash table lookup. Unfortunately, your case is the worst one because you have so many items in the object. There is no difference how you access the property, obj.field and obj['filed'] it's the same.

    It's also worth to mention that the complexity isn't always equal to complexity of a hash table lookup, it's faster in much cases. Modern JS engines use techniques called hidden classes and inline caching to speed up the lookup. It's a pretty big question, how these techniques work, I've explained it in the another answer.

    Some relative resources:

    • JavaScript engine fundamentals: Shapes and Inline Caches and a YouTube video as well.
    • Fast properties in V8
    • A tour of V8: object representation
    • JavaScript Engines Hidden Classes (and Why You Should Keep Them in Mind)
    0 讨论(0)
提交回复
热议问题