SOS

Shane O'Sullivan's technical blog… really ties the room together

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

About these ads

3 Responses to “Tip: Declare regular expressions once and reuse for performance win”

  1. Terry said

    Are there any caveats when reusing Javascript regex objects?

  2. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 535 other followers

%d bloggers like this: