Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance differences between jquery.inArray() vs Object.hasOwnProperty()?

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?

like image 765
Gaurav Avatar asked May 20 '11 17:05

Gaurav


3 Answers

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.

like image 103
James Montagne Avatar answered Jan 09 '23 00:01

James Montagne


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

like image 41
Claudio Avatar answered Jan 09 '23 00:01

Claudio


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.

like image 26
Lyn Headley Avatar answered Jan 08 '23 23:01

Lyn Headley