Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to check if a number is in a set?

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)

like image 507
pixartist Avatar asked Oct 20 '25 14:10

pixartist


2 Answers

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.

like image 147
Pointy Avatar answered Oct 23 '25 02:10

Pointy


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
like image 23
vhs Avatar answered Oct 23 '25 02:10

vhs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!