JavaScript Performance – Array.indexOf vs Object Hash Lookup

arraysjavascriptobject

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?

Best Answer

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