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.
- The compiler notices that the array is a string array (type can be determine at compile time, no runtime checks necessary).
- In the loop, since you use
===, builtin CPU op codes to compare strings (
repe cmpsb) can be used. So no functions are being called (unlike in any other test case)
- After the first loop, everything important (the array, the strings to compare against) is in CPU caches. Locality rulez them all.
All the other approaches need to invoke functions and locality might be an issue for the regexp versions because they build a parse tree.
I have added two more tests : http://jsperf.com/finding-components-of-a-url/2
The single regExp is fastest now (on Chrome). Also regExp literals are faster than string literals converted to RegExp.