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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With