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.
Even if someone does extend the prototype, you can use hasOwnProperty property to exclude these members. This is exactly what Sugar.js recommends:
var s = 'cat', key;
for(key in s) {
if(s.hasOwnProperty(key)) {
console.log(key);
}
}
Now according to Sugar, for..in is the accepted loop for object literals, but you can also use an iterator like $.each for jQuery or _.each for Underscore.js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With