Reputation:
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 have a JavaScript object containing user information where the keys are the user's IDs and the values are each user's information.
The reason I ask this is because I would like to use the angular-ui-select
module to select users, but I can't use that module with a Javascript object - it requires an array.
How much, if anything, am I sacrificing by switching from a lookup by key, to a lookup by iteration?
By key:
var user = users[id];
By iteration
var user;
for (var i = 0; i < users.length; i ++) {
if (users[i].id == id) {
user = users[i]; break;
}
}
Upvotes: 22
Views: 32330
Reputation: 11620
This problem touches all programming languages. It depends on many factors:
In your example map would be a better solution. Secondly, you need to add a break to your 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:)
If You wish to use a map, then:
type userById = Map<any, User>
users.forEach(user => userById.set(user.id, user));
This will be the fastest solution, If you wish to search multiple times.
Upvotes: 4
Reputation: 1104
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:
Upvotes: 21
Reputation: 9
associative arrays are much slower then arrays with numbered indexes, because associative arrays work by doing string comparisons, which are much, much slower then number comparisons!
Upvotes: -6