3

What's the fastest way to find the index of an item in a list or object in Javascript / AS3? I'm asking this for both because the syntax is similar for both these languages.

Assuming:

myArray = ["one", "two", "three"];
myObject = {one:1, two:2, three:3};

Which is the fastest and in which case would you want it or not?

  • Array.indexOf(x)
  • myObject[x] != null
  • x in myObject
  • something else?
1
  • usually, using primitive arrays and accessing using bracket notation is the fastest. but I'm sure a simple Google search will come up with your answer Commented Dec 7, 2012 at 5:33

3 Answers 3

3

Using an object doesn't sound like a good idea, as re-indexing will be a heavy operation and will wipe out the access performance gains if any. Array.indexOf(x) seems to be the way to go.

Sign up to request clarification or add additional context in comments.

Comments

2

Objects are implemented using efficient hash tables, so looking up a key will be O(1). If your values to "find" are strings and their positions are static, this will be quite fast. Checking for boolean existance can be done with key in obj, getting the stored index will be obj[key] || -1.

If you're searching for more complex objects (which are not serializable to strings easily), you will need to use an Array. Array.indexOf does a search with O(n), which is okay if you don't do it too often. Checking for existance will be arr.indexOf(item) != -1, getting the index just arr.indexOf(item).

Comments

1

I have done some tests on native indexOf and binary search of needed index. Here are results on 10 000 items array.

  • value | IndexOf | binary search
  • 1 | 0.003 | 0.013
  • 5000 | 1.546 | 0.016
  • 9990 | 3.105 | 0.015

Test are done in node v8 environment, but seems native indexOf is using loop to find needed index. Here are a link to binary search http://oli.me.uk/2013/06/08/searching-javascript-arrays-with-a-binary-search/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.