Quantcast
Viewing all articles
Browse latest Browse all 57

Tip: Declare regular expressions once and reuse for performance win

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


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 57

Trending Articles