Just think about it. Regular expressions are powerful because they are expressive and very flexible (with features like forward lookup, greedy consumption and backtracking). It will almost always be worth that little.
If you need raw speed (and you are ready to give up expressiveness), you may find that it bypasses ordinary expressions faster and just evaluates the string, for example, with the following pseudo-code:
def hasThreeAlphaNums(str): alphanums = 0 for pos = 0 to len(str) - 1: if str[pos] in set "[a-zA-Z0-9]": alphanums++ if alphanums == 3: return true return false
It is a parser (very simple in this case), a tool that can be even more powerful than regular expressions. For a more specific example, consider the following C code:
#include <ctype.h> int hasThreeAlphaNums (char *str) { int count = 0; for (int ch = *str; ch != '\0'; str++) if (isalnum (ch)) if (++count == 3) return 1; return 0; }
Now, regarding whether it’s faster or faster for this particular case, which depends on many factors, for example, whether the language is interpreted or compiled, how effective the regular expression under covers, etc.
So why the mantra of optimization is “Measure, don't guess!” You must evaluate the opportunities in your target environment.
paxdiablo
source share