There are several ways in which one might imagine optimzing a regular expression that is often used.
The first is to simply create it each time using new RegExp(), as follows:
function insideLoop() {
var it = iterations;
for(var i=0; i<it; i++) {
var myRegExpIn = new RegExp("there");
myRegExpIn.test("hello there man");
}
}
The second way would be to skip the "new RegExp()" stuff, since it's just a static string that we're matching against, and, instead, use this:
function insideLoop2() {
var it = iterations;
for(var i=0; i<it; i++) {
/there/.test("hello there man");
}
}
What would appear to be the obvious way of optimizing this if it's done often enough, is to create a global variable for this RegExp and just always reference that, like so:
var myRegExpOut = /there/;
function outsideLoop() {
var it = iterations;
for(var i=0; i<it; i++) {
myRegExpOut.test("hello there man");
}
}
Click the 'Measure' button below to see how they stack up with run 10,000 times: