I have a situation that I’m trying to make work with an array, but I just don’t think it will. I want to have a list of objects, each with a unique ID, and I want to be able to easily reference a particular object without having to loop through the array searching for that ID.
If I use an object I can easily use the unique ID as the key and the object as the value. However, if I use an object instead of an array I’ll have to use a for...in loop, and I know there are issue surrounding that if someone using my code has extended Object.prototype.
So here’s my question:
Is it really that common that people extend Object.prototype that I should be weary of using it? Are there other reasons why I wouldn’t want to use a for...in loop?
On the other hand, is the performance hit of looping through an array looking for a unique ID so minimal that I shouldn’t worry about?
(For the record, the array will probably have fairly few elements in it, but I’ll be accessing it very frequently. Also, the code I’m writing will be a jQuery plugin, so I have no control over what other bad code people are combining it with.)
UPDATE:
Based on advice from @nnnnnn, I set up a jsperf test and here are the results:
http://jsperf.com/accessing-object-properties-vs-iterating-over-arrays
Basically, though the object way is slightly faster, the difference is negligible. Still, using for...in with hasOwnProperty seems cleaner.
No it’s not common, but it does happen. You should use a for..in loop anyway, but with
.hasOwnProperty()as shown in the other answers.I can’t think of any reasons to not use a for..in (on an object; obviously you don’t use it on an array).
Well you mentioned that your array won’t have many elements, but still I think that even if it performed well it would needlessly complicate your code given that you don’t have to do it at all for objects. On the other hand using
.hasOwnProperty()is a minor complication that effectively becomes part of the syntax of each for..in.You can setup a test of the performance here: http://jsperf.com/