O'Reilly logo

High Performance JavaScript by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Regular Expression Optimization

Incautiously crafted regexes can be a major performance bottleneck (the upcoming section, Runaway Backtracking, contains several examples showing how severe this can be), but there is a lot you can do to improve regex efficiency. Just because two regexes match the same text doesn’t mean they do so at the same speed.

Many factors affect a regex’s efficiency. For starters, the text a regex is applied to makes a big difference because regexes spend more time on partial matches than obvious nonmatches. Each browser’s regex engine also has different internal optimizations.[4]

Regex optimization is a fairly broad and nuanced topic. There’s only so much that can be covered in this section, but what’s included should put you well on your way to understanding the kinds of issues that affect regex performance and mastering the art of crafting efficient regexes.

Note that this section assumes you already have some experience with regular expressions and are primarily interested in how to make them faster. If you’re new to regular expressions or need to brush up on the basics, numerous resources are available on the Web and in print. Regular Expressions Cookbook (O’Reilly) by Jan Goyvaerts and Steven Levithan (that’s me!) is written for people who like to learn by doing, and covers JavaScript and several other programming languages equally.

How Regular Expressions Work

In order to use regular expressions efficiently, it’s important to understand how they work their ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required