Effective Javascript Array Search

If I have a white list of strings that I want to check everything the user enters into my javascript program, what is the most efficient way to do this? I could just have an array and scroll through it until a match is found, but this is O (N). Is there a way to do this better and not require any kind of key value search, just checking if that value exists?

EDIT: I assume that what I'm looking for is equivalent to a set in C ++, where I can simply check if the value that I give already exists in the set.

+4
performance javascript
source share
3 answers

Just make a simple js object instead of an array.

var whitelist = { "string1":true, "string2":true } 

and then you can just check if(whitelist[str]) to check if this is available.

Or use if(str in whitelist) .

I expect the former to have slightly better performance (I have not tested this), but the latter is more readable and makes the goal understandable. Thus, your choice of them is better suited.

+1
source share

Array sorting, using binary search to search.

or

Create an object in which the key is an element and use the hash search whitelist [value]! = Undefined

+1
source share

I think you will find that keyword search is almost identical in performance for any implementation of a set without values. (Many standard libraries actually just implement a set using a map)

+1
source share

All Articles