Tip: Declare regular expressions once and reuse for performance win
Posted by Shane O'Sullivan on September 22, 2011
A pattern I see quite often in JavaScript is of people using a regular expression in a loop, e.g.
for (var i = 0; i < array.length; i++) {
array[i].match(/something/);
}
The naive assumption is that a regex is some special native thing, like a boolean. However regular expressions have a cost to construct, which you can see in this performance test –
http://jsperf.com/creating-a-regex-in-and-outside-a-loop
So, if you’re using a regular expression in JavaScript more than once, declare it first and reuse it to see a dramatic performance gain

Terry said
Are there any caveats when reusing Javascript regex objects?
Shane O'Sullivan said
Not that I can think of.
Johnny said
The process of constructing an array of matches is far slower than building the regex itself, although it’s of course still VERY important to define all your regexps outside the loop.
I rewrote the performance test to have far more detailed results for various usage cases and outside-the-loop is about 50% faster in all cases:
http://jsperf.com/creating-a-regex-in-and-outside-a-loop/3