Fastest way to search string in javascript

Viewed 9748

I have a hidden field on my page that stores space separated list of emails. I can have maximum 500 emails in that field.

What will be the fastest way to search if a given email already exists in that list? I need to search multiple emails in a loop

  1. use RegEx to find a match

  2. use indexOf()

  3. convert the list to a javascript dictionary and then search

If this is an exact duplicate, please let me know the other question. Thanks

EDIT: Thanks everyone for your valuable comments and answers. Basically my user has a list of emails(0-500) in db. User is presented with his own contact list. User can then choose one\more emails from his contact list to add to the list. I want to ensure at client side that he is not adding duplicate emails. Whole operation is driven by ajax, so jsvascript is required.

6 Answers

I know this is an old question, but here goes an answer for those who might need in the future.

I made some tests and the indexOf() method is impossibly fast!

Tested the case on Opera 12.16 and it took 216µs to search and possibly find something.

Here is the code used:

console.time('a');
var a=((Math.random()*1e8)>>0).toString(16);
for(var i=0;i<1000;++i)a=a+' '+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16);
console.timeEnd('a');
console.time('b');
var b=(' '+a).indexOf(((Math.random()*1e8)>>0).toString(16));
console.timeEnd('b');
console.log([a,b]);

In the console you will see a huge output.

The timer 'a' counts the time taken to make the "garbage", and the timer 'b' is the time to search for the string.

Just adding 2 spaces, one before and one after, on the email list and adding 1 space before and after the email, you are set to go.

I use it to search for a class in an element without jQuery and it works pretty fast and fine.

Related