Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: what lookup is faster: array.indexOf vs object hash?

I have to perform a LOT of lookups, while parsing xmlStream if i need some tag or not.

I can do it with array.indexOf method (i have about ~15 items in array) or using object[key] lookup.

Second solution seems more efficient in theory for me, but does not look line nice in my code. But if it is really more efficient, i would leave it as it is.

E.g.:

var tags = [
    'tag1',
    'tag2',
    'tag3',
    ...
];

var tags2 = {
    'tag1' : null,
    'tag2' : null,
    'tag3' : null,
}

tags.indexOf(value) // exists?
tags2[value] // exists?
like image 201
avasin Avatar asked Aug 26 '15 19:08

avasin


People also ask

Which is faster includes or indexOf?

History. indexOf was created way before includes . Seems like the difference in performance is not that obvious. My mobile Firefox shows that indexOf is actually faster.

Is indexOf faster than for loop?

It seems in large arrays indexOf may be a faster choice. EDIT: Based on more tests, indexOf seems to run faster than a for loop in the version of Safari I'm using (5.0. 3) and slower in just about everything else.

How does indexOf work?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.


2 Answers

Object key lookup is faster than Array.indexOf(). You can check it on jsperf.

Test Results:

Array

Index of 10000 items: 26,547 Operations/sec
Index of 100000 items: 2,493 Operations/sec

Object

Lookup key of 10000 items: 152,115 Operations/sec
Lookup key of 100000 items: 150,450 Operations/sec

like image 161
StefansArya Avatar answered Oct 19 '22 05:10

StefansArya


Well, the performance depends on your set size and your access pattern. In general, the indexOf is O(n) and hash is O(1), however, since you only have about 15 items in the set and let's say each access is completely independent and equiprobable, the advantage of hash isn't really there.

like image 39
baozi Avatar answered Oct 19 '22 07:10

baozi