A hopefully faster Bidirectional
While the new method includes is very nice, the support is basically zero for now.
It's long time that i was thinking of way to replace the slow indexOf/lastIndexOf functions.
A performant way has ben already found, looking at the top answers. From those i choosed the
contains function posted by @Damir Zekić which should be the fastest one. But also states that the benchmarks are from 2008 and so outdated.
I also prefer
for but for not a specific reason i ended writing the function with a for loop.it could be also done with a
I was curious if the iteration was much slower if i check both sides of the array while doing it. Apparently no, and so this function is around 2x faster than the Top voted ones. Obiovsly it's also faster than the native one.This in a real world environment, where you never know if the value you are searching is at the beginning or at the end of the array.
When you know you just pushed an array with a value, using lastIndexOf remains probably the best solution, but if you have to travel trough big arrays and the result could be everywhere this could be a solid solution to make things faster.
if(a[c]==b)return c; //or this[c]===b
if(a[e=d-1-c]==b)return e; //or a[e=d-1-c]===b
As test i created an array with 100k entries.
Three queries : at the beginning, in the middle & at the end of the array.
I hope you also find this intresting and test the performance.
note: as you can see i slightly modified the
contains function to reflect the indexOf & lastIndexOf output.(so basically
true with the
-1). That shouldn't harm it.
The array prototype variante
if(this[c]==b)return c; //or this[c]===b
if(this[e=d-1-c]==b)return e; //or this[e=d-1-c]===b
The function can also be easely modified to return true or false or even the object, string or whatever it is.
if you have any questions just ask.
And here is the
How is this possible?
I think that the simple calculation to get the reflected index in an array is so simple that it's 2 times faster than doing an actual loop iteration.
Here is a complex example doing 3 checks per iteration, but this is only possible with a longer calculation which causes the slow down of the code.