XML technologies / Regular expressions / The art of writing regular expressions / Programming techniques for faster regexes

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

We have examined internal optimizations in traditional NFAs. None implements them all, and future versions may change them. Studying them still teaches what a regex engine does quickly or slowly. Together with understanding traditional NFAs, this knowledge helps in three ways:

Make optimizations obvious

Write regexes so opportunities are easily recognized. For example, with ˹xx*˼ rather than ˹x+˼, fixed-string optimization (see Searching for individual characters or fixed substrings) or First-character optimization is easier to recognize.

Imitate optimizations

If an engine lacks an optimization, explicit regex programming may imitate it. We will examine this example: prefix ˹klipp|klar˼ with lookahead ˹(?=k)˼ to imitate first-character optimization when the engine does not notice every match starts with ›k‹.

Lead the engine to a match

Knowing traditional NFAs, we can guide them faster. Reconsider ˹klipp|klar˼. Both branches begin with ˹kl˼. If the first fails on ˹kl˼, retesting ˹kl˼ in the second is redundant. Factor ˹kl˼ out, writing ˹kl(?:ipp|ar)˼. Now ˹kl˼ is tested once, and expensive alternation runs only when needed. The initial literal may enable further optimizations.

Manual optimization has pitfalls:

One striking example: in a Perl script you find ˹(000|999)$˼ whose captures are unused. Replacing them with noncapturing parentheses seems faster, but surprisingly slows it by several orders of magnitude, over a thousandfold, by preventing an end-anchor optimization (see Line- and string-anchor optimizations). Noncapturing parentheses are usually faster in Perl, but pathological exceptions exist.

Only benchmarks on actual data reveal whether a change helps. Weigh the tradeoffs. With these cautions, here are techniques for getting the most from an engine.

Use common sense

Common sense is among the most effective optimizations.

Avoid recompilation

Compile only as often as needed. Object-oriented interfaces (see Procedural and object-oriented approaches) give direct control. For repeated matching in a loop, create and compile the object before, outside the loop.

With procedural interfaces like Tcl or GNU Emacs, keep the number of distinct regexes used in a loop below the cache size (see Compilation caching with procedural interfaces).

With integrated regexes, as in Perl, avoid variable interpolation inside loops: it requires at least reevaluation, even for unchanged values. Perl provides workarounds; see Regex compilation, /o, qr/.../, and efficiency.

Use noncapturing parentheses

If captured text is unused, prefer noncapturing parentheses ˹(?:...)˼ (see Solution 5). They avoid saving captured text and simplify state stored for backtracking. They may also enable optimizations such as eliminating unnecessary parentheses (see Eliminating unnecessary parentheses).

Avoid unnecessary parentheses

Use parentheses where needed; unnecessary ones can block optimizations. Use ˹(.)*˼ only if you need the last character matched by ˹.*˼. Obvious, perhaps, but this section is about common sense.

Avoid unnecessary character classes

This also seems obvious, yet beginners often write things like ˹^.*[:]˼. A single-character class adds overhead without benefit.

With metacharacters like ˹[.]˼ or ˹[*]˼, perhaps the programmer does not know escapes such as ˹\.˼ and ˹\*˼. This also occurs with whitespace in  free-spacing mode.

First-edition readers may use expressions like ˹^[Ff][Rr][Oo][Mm]:˼ instead of case-insensitive mode. Old Perl versions implemented that mode inefficiently, hence my recommendation then. That limitation disappeared years ago.

Put anchors at the start

A regex beginning with ˹.*˼ can almost always be prefixed with ˹^˼ or ˹\A˼ (see Beginning of line or string). Failure at the string's start is unlikely to turn into success at the next positions. Explicit or internally optimized anchors (see Transmission optimizations) save much unnecessary work.

  

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top