JavaScript Performance Tip: Precompile Your Regular Expressions

jsperf regex feature

When it comes to speeding up your web applications, the little things can make quite a difference. One of the ways you can improve the performance of your application is by “precompiling” any regular expressions you use. But wait, JavaScript is an interpreted language. How can a regular expression be precompiled? Well, take a look at the following code:

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>";

myHtml.replace(/test/g, "kittens");

When we run these snippets through JsPerf we get the following (in Chrome):

jsPerf regex

Here’s a breakdown of the performance across multiple browsers:

jfperf regex chart

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.

Write us your thoughts about this post. Be kind & Play nice.

Leave a reply.