Answer the question
In order to leave comments, you need to log in
And what is easier for JS - a simple condition or a regexp?
For example, (x == 'a' || x == 'b' || x == 'c') or x.match(/^(?:a|b|c)$/)?
Answer the question
In order to leave comments, you need to log in
Made some measurements in chrome.
On average, the first option (10,000 normal comparisons) takes 30-45 ms. The second is 20-25.
If it is equal to , then each time it will be checked only and then the first option passes in 25-35 ms. Those. in this particular example, regexps win.
But in other cases, the result may be different.
var x = '1',
times = 10000,
start1 = +new Date();
for (var i=0; i<times; i++) {
if (x == 'a' || x == 'b' || x == 'c') {
}
}
var time1 = +new Date() - start1,
start2 = +new Date();
for (var i=0; i<times; i++) {
if (x.match(/^(?:a|b|c)$/)) {
}
}
var time2 = +new Date() - start2;
console.log(time1, time2)
Your tests and results are strange.
jsperf.com/if-vs-regexp-match
Of course if is an order of magnitude faster.
A regular expression is a function call, which is a more expensive process.
What does "easier" mean? Runs faster? Of course, the first, because regexps must first be compiled, then work with them ... This is clearly more complicated than just comparing lines.
In general, it seems to me that this is some kind of savings on matches. Why is the performance of this code so important to you?
It is better to use the usual conditions. Yes, you can win 1-10ms with regexps, but it will make your code so badly readable that it makes you wonder if the game is worth the candle.
Using "===" instead of "==" will allow the first option to win even more convincingly in this pointless competition (in FF at least).
I would use something like this:
if (possibleValues.indexOf(item)) >= 0
in this case it doesn't matter. unless you have such checks performed so often that it affects performance.
with if'ami it is a little more evident, but in some situations without regular expressions it will be heavy.
for example, I use a function to check if a string is a valid e-mail:
return /^[0-9a-z_\.][email protected][0-9a-z_\^\.]+\.[a-z]{2,6}$/i.test(s);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question