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
-
use RegEx to find a match
-
use indexOf()
- 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.
Instead of looking for the fastest solution, you first need to make sure that you’re actually having a correct solution. Because there are four cases an e-mail address can appear and a naive search can fail:
user@example.comuser@example.com ...... user@example.com... user@example.com ...Now let’s analyze each variant:
To allow arbitrary input, you will need to escape the input properly. You can use the following method to do so:
To match all four cases, you can use the following pattern:
Thus:
Using
indexOfis a little more complex as you need to check the boundaries manually:This one is rather quite simple:
Now to test what variant is the fastest, you can do that at jsPerf.