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?
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?
- usually, using primitive arrays and accessing using bracket notation is the fastest. but I'm sure a simple Google search will e up with your answer – kennypu Commented Dec 7, 2012 at 5:33
3 Answers
Reset to default 3Using 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.
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 plex 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)
.
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/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744243744a4564826.html
评论列表(0条)