I have a situation where I can choose to implement a collection of string keys as an object:
$.each(objects, function (key, object) {
collection[key] = "doesn't matter";
});
or an array:
$.each(objects, function (key, object) {
collection.push(key);
});
I'd like to be able to quickly determine whether or not the collection contains a given key. If collection is an object, I can use:
if (collection.hasOwnProperty(key_to_find)) { // found it!... }
else { // didn't find it... }
If collection is an array, I can use:
if ($.inArray(key_to_find, collection)) { // found it!... }
else { // didn't find it... }
I'd imagine using JavaScript's built-in hasOwnProperty would be faster than jQuery's inArray(), but I'm not entirely sure. Does anyone know more about the performance differences between these two methods? Or, is there a more efficient alternative here that I am not aware of?
If we're talking just how long it takes to check, then there's really no contest:
http://jsperf.com/array-vs-obj
hasOwnProperty is way way faster for the reasons stated by others.
Mmmh, if the collection is an array you can also use the native indexOf on it, no? https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
The array method is slower, because it requires linear time to find an element in the array (the code must step through potentially every element). hasOwnProperty will be much faster as it can use a hash table lookup, which occurs in constant time.
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