JavaScript object vs. array lookup performance

前端 未结 3 779
無奈伤痛
無奈伤痛 2021-02-05 09:26

What is the performance difference between retrieving the value by key in a JavaScript object vs iterating over an array of individual JavaScript objects?

In my case, I

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 10:22

    The answer to this is browser dependent, however, there are a few performance tests on jsperf.com on this matter. It also comes down to the size of your data. Generally it is faster to use object key value pairs when you have large amounts of data. For small datasets, arrays can be faster.

    Array search will have different performance dependent on where in the array your target item exist. Object search will have a more consistent search performance as keys doesn't have a specific order.

    Also looping through arrays are faster than looping through keys, so if you plan on doing operations on all items, it can be wise to put them in an array. In some of my project I do both, since I need to do bulk operations and fast lookup from identifiers.

    A test:

    http://jsben.ch/#/Y9jDP

提交回复
热议问题