JavaScript object vs. array lookup performance

前端 未结 3 784
無奈伤痛
無奈伤痛 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:16

    This problem touches all programming languages. It depends on many factors:

    • size of your collection -arrays will get slower when you are searching for the last key, and array is quite long
    • can elements repeat them selves-if yes, than you need a array. If no: you need either a dictionary (map) or you need to write a add method that for each add will iterate your array and find possible duplicates-that can be troublesome, when dealing with large lists
    • average key usage - you will lose performance, if the most requested userId is at the end of the list.

    In your example map would be a better solution. Secondly, you need to add a break to yor code:)

    var user;
    
    for (var i = 0; i < users.length; i ++) {
      if (users[i].id == id) {
         user = users[i]; break;
      }
    }
    

    Or you will lose performance:)

提交回复
热议问题