consider
a = ['1','2','3','4','5']
for(var i = 0; i < a.length; i++) { if (a[i] == 3) console.log('found it!') }
and
a = {'1': true, '2': true, '3': true, '4': true}
a['3']
Which will be faster and why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
An object lookup will on average be much faster when trying to find a random element, especially when you are searching through a large number of items. This is because the underlying algorithm to do so is a B-tree search which has a time complexity of O(log n) and allows it to quickly look up an items membership without having to check it against each element in the object.
This is opposed to when searching in an array you must check each element before deciding if is not in the array which has a linear time complexity of O(n).
Here is the benchmark showing object lookup is faster: http://jsperf.com/array-vs-objv2/6