This came as a huge surprise for me, and I'd like to understand this result. I made a test in jsperf that is basically supposed to take a string (that is part of a URL that I'd like to check) and checks for the presence of 4 items (that are in fact, present in the string).
It checks in 5 ways:
- plain indexOf;
- Split the string, then indexOf;
- regex search;
- regex match;
- Split the string, loop through the array of items, and then check if any of them matches the things it's supposed to match
To my huge surprise, number 5 is the fastest in Chrome 21. This is what I can't explain.
In Firefox 14, the plain indexOf is the fastest, that one I can believe.
indexOf
breaks out earlier, but I could imagine that the string is just too short for this to have an impact (that does not explain the results for Firefox though :-/). – FreebootindexOf
).indexOf
always has to iterate over the array until it finds a match and you do this four times, so you potentially have to iterate over the whole array four times compared to just one time with yourwhile
loop. Similar for the first test case (four times iterating over the string). – Freeboot