XML technologies / Regular expressions / The art of writing regular expressions / Common optimizations / Optimizing the regex engine

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

 

Concatenating literals

Perhaps the most obvious and simplest optimization: the engine treats ˹abc˼ as one unit rather than three separate pieces, “˹a˼, then ˹b˼, then ˹c˼”. Processing that unit at once avoids three iterations of the engine’s internal loop.

 

Simple-quantifier optimization

When a quantifier applies to something simple, such as a literal character or character class, handling it outside the NFA’s normal progression is often advantageous. An engine’s central loop must be general enough for all constructs, but general programming is almost always slow programming. This optimization handles simple quantifiers in a small specialized, faster loop instead of the general one.

The expressions ˹.*˼ and ˹(?:.)*˼ are logically identical, but depending on the system, the simple ˹.*˼ is much faster. Some examples: Sun’s Java regex package shows only a 10% difference; Ruby and .NET show a factor of 2.5; in Python, ˹(?:.)*˼ is 50 times as fast, and with PCRE/PHP, even 150 times. Perl uses the next section’s optimization, so ˹.*˼ and ˹(?:.)*˼ are equally fast. Also note the following box’s discussion of these benchmark figures.

 

This chapter’s benchmarks

Most benchmarks here are relative figures comparing expressions within the same language. Above, Sun’s Java package gained 10% from optimization, .NET gained a factor of 2.5, and PCRE a factor of 150. Perl showed a factor of one: no difference.

What does this tell us about speeds across languages? Nothing at all. PCRE’s enormous factor of 150 might mean an excellent optimization or a particularly slow unoptimized version. I rarely compare languages directly; that mostly interests people boasting about their favorite language.

For what it is worth, such a gap between Java’s 10% and PCRE’s factor of 150 merits a comparison. PCRE’s unoptimized version is about eleven times slower than Java’s, but its optimized version is thirteen times faster. Optimized Java and Ruby are about equal; unoptimized Ruby is about 2.5 times slower than Java and only 10% slower than Python. Among optimized versions, however, Python is twenty times faster.

All are slower than Perl’s engine. In Perl, both regex forms are equally fast and about 10% faster than Python’s fastest. Every implementation has strengths and weaknesses, however, and these numbers cover only one very specific test.

 

Removing unnecessary parentheses

If an implementation can determine that ˹(?:.)*˼ is exactly equivalent to ˹.*˼, it can discard the parentheses.

 

Removing unnecessary character classes

A single-character class is rather silly: extra overhead with no benefit. Yet some write a literal dot as ˹[.]˼; a clever implementation treats it just like ˹\.˼.

 

The character after a lazy quantifier

With a lazy quantifier, as in ˹"(.*?)"˼ , the engine normally alternates between the quantified subexpression, here dot, and the following character, ˹"˼. For this and other reasons, lazy quantifiers are generally slower than greedy ones, particularly with simple-quantifier optimization. Inside capturing parentheses, repeated entry and exit add still more overhead.

If a literal character follows a lazy quantifier, it can behave like an ordinary greedy quantifier until that character appears. Specialized code again replaces the general engine loop, scanning for the literal and avoiding the normal next-attempt iteration until it is found.

One variant checks a character class instead of a single literal; for example, with ˹['"](.*?)["']˼ it looks ahead for ˹['"]˼. This resembles the first-character optimization.

 

Detecting excessive backtracking

In the problem in Back to reality, certain quantifier combinations produced exponential backtracking and eternal matching. A simple solution counts backtracks and quits when they become excessive. Useful normally, but it imposes an artificial limit on subject length.

For example, limiting backtracking to 10,000 operations means ˹.*?˼ cannot match text over 10,000 characters, since every matched character triggers a backtracking operation. Such text is common, especially on Web pages, making an arbitrary limit unfortunate.

Some implementations limit the backtracking stack for other reasons. Python, for example, has a maximum stack size of 10,000, restricting subject length for certain regexes.

This hampered benchmarking for the book. Meaningful results should measure the engine’s work, making repeated application overhead negligible. I generated huge strings and applied expressions such as ˹"(.*)"˼, ˹"(.)*"˼, ˹"(.)*?"˼ or ˹"([^"])*?"˼ only a few times. Not every implementation allowed this; I had to shorten subjects to avoid stack overflow. See Tcl benchmarks for an example.

Avoiding exponential, superlinear behavior

Better still, detect exponential or superlinear behavior and avoid eternal matching. The engine records the position of each subexpression quantified by star or plus.

Detecting superlinear behavior is fairly easy: normally a quantifier should not iterate more times than there are subject characters. Exceeding that strongly suggests exponential matching. Diagnosis is only the beginning; deciding which attempts are unnecessary is much harder. Still, short-circuiting the regex to prevent eternal matching is work well spent.

An unfortunate side effect hides badly written, inefficient regexes from programmers. Even optimized, a regex may remain far slower than necessary, but no longer noticeably so: a hundredth of a second instead of hours is imperceptible to users, yet an eternity for a computer.

The potential gain nevertheless justifies this optimization. Many users ignore efficiency, barely understand regexes, and are glad when something works at all. Perhaps you were one; I hope this book ends that.

 

Discarding unnecessary saved states with possessive quantifiers

After an ordinary greedy quantifier matches, it leaves a skip-this-option state for each iteration. Possessive quantifiers explicitly discard these states (see Possessive quantifiers). But they can be discarded during quantifier processing as the next iteration begins; at least one saved state is needed during matching.

This uses less memory than discarding everything at the end. With ˹.*˼, one state per matched character can consume enormous memory on long subjects.

 

Automatic possessification

In an example in How regex engines work (see Faster failures with atomic groups), we applied ˹^\w+:˼ to ›Subject‹ . Initially, ˹\w+˼ matches to the string’s end, where colon fails. Backtracking then reclaims every character, doing much useless work to discover that ˹:˼ matches none of them. We avoided this with atomic parentheses, ˹^(?>\w+):˼, or a possessive quantifier, ˹^\w++:˼.

An excellent implementation could do this itself. During compilation, it can notice that the item following a quantifier can never be matched by the quantified subexpression, making that quantified subexpression effectively possessive.

I know no system implementing this optimization, but hope developers accept the challenge. I believe the gain could be substantial.

 

Small quantifiers

Some write ˹\d\d\d\d˼; others prefer brace quantifiers and write ˹\d{4}˼. Is one more efficient? Almost certainly for an NFA, but which depends on the implementation. With optimized quantifiers, ˹\d{4}˼ is probably faster, though the other might be better optimized too. Confusing? Indeed.

My measurements show ˹\d{4}˼ up to 20% faster in Perl, Python, PHP/PCRE, and .NET. Conversely, Ruby and Sun’s Java package make ˹\d\d\d\d˼ faster, sometimes several times faster. Small quantifiers therefore help some programs and hurt others. But it gets more complicated.

Compare ˹====˼ and ˹={4}˼. Here the repeated part is literal, and the engine may recognize a literal substring more easily in ˹====˼. If so, it can apply the huge-saving literal-substring optimization (see Literal-string optimization within text). Python and Sun’s Java package do exactly that, making ˹====˼ up to a hundred times faster than ˹={4}˼.

Perl, Ruby, and .NET recognize this for both ˹====˼ and ˹={4}˼, making them equally fast and hundreds or thousands of times faster than ˹\d\d\d\d˼ or ˹\d{4}˼.

 

Which matching results are actually needed?

If an engine can determine that certain results, such as captured text, will never be used later, it can omit the associated work. This depends heavily on the language, though a special option sometimes exists.

Tcl does this: parentheses capture text only when explicitly requested. Conversely, .NET offers an option explicitly disabling capture by capturing parentheses.

  

 

 

 

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