admin管理员组文章数量:1399910
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/
本文标签: javascriptFastest way to find item in arrayobjectStack Overflow
版权声明:本文标题:javascript - Fastest way to find item in arrayobject - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744243743a2596910.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论