What is the fastest method to check if a number is in a list in Javascript?
I know about indexOf >= but it seems rather slow to me.
I have to perform millions of checks per second and the list is rather short (max ~10 entries)
What is the fastest method to check if a number is in a list in Javascript?
I know about indexOf >= but it seems rather slow to me.
I have to perform millions of checks per second and the list is rather short (max ~10 entries)
Try it out at jsperf but I suspect that using an object and setting up the numbers as properties would be faster than an array search.
var theList = { 1: true, 2000: true, 253: true, -12077: true, ... };
if (theList[ someNumber ]) { // see if some number is in the list
Now, that said, you're not going to be able to do anything useful in JavaScript in a web browser millions of times per second, except perhaps on extremely high-end machines that aren't doing much else.
Well it is better to use indexof()
As an alternative which is not appreciated in your case is to use Enumerable#include
You can use Enumerable#include but I doubt if it is faster than indexof()
Something like:-
[1, 2, '3', '4', '5'].include(3);
If you're looking for speed of comprehension, use array.includes
:
[-1, 1, 2].includes(0) // false
[-1, 1, 2].includes(-1) // true
[-1, 1, 2].includes(-2) // false
[-1, 1, 2].includes(2) // true
[-1, 1, 2].includes(3) // false