var preCompiledReplaceRegex = /test/g;
myHtml = "<span>This is a test</span><div>Of a regex</div><p>test</p><em>test</em>";
myHtml.replace(preCompiledReplaceRegex, 'kittens'); // Compiled Regex
By storing the regex in a variable before using it to replace the word “test” with the word “kittens”, we increase the performance of the code. When a regex is used and not stored in a variable, it gets reevaluated every time the replace method is called. By storing it in a variable before use, we guarantee that the expression only gets evaluated once. Let’s rewrite the above example, but use the regex directly in the call to the replace method:
var myHtml = "<span>This is a test</span><div>Of a regex</div><p>test</p><em>test</em>";
When we run these snippets through JsPerf we get the following (in Chrome):
Here’s a breakdown of the performance across multiple browsers:
When I ran this test in IE9, JsPerf calculated a 9% speed difference between the precompiled regex vs the non-precompiled one; that’s nothing to sneeze at.