Which is the faster way (in character level) when checking if two strings or RegExp match exactly? If the string is extremely long or have to check many times?
-
str == str_or_regexp || str =~ str_or_regexp -
str[str_or_regexp] == str
Or there is better way?
We don’t know str_or_regexp is a string or a regular expression until runtime.
When all else fails, run some tests:
I got these results:
That indicates that your first method is a little bit faster than your second.
However, if the strings are not equal and the
||doesn’t “short circuit”, you’ll get aTypeError. You can’t pass a string to=~. So you should probably replaced that withstr.match(t), which gave me these results:In that case, your first method fared much worse for regexps, but the second was about the same.
Like I said, just run some tests on real data and see what happens.