XML technologies / Regular expressions / The art of writing regular expressions / Common optimizations / Optimizations before searching

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

A good regex implementation may save work before searching. Sometimes it determines the regex cannot match and avoids applying it altogether.

 

Compilation caching

Our small mail program from Extended introductory examples (see A small mail program) centers on a loop processing each header line:

while (...) {
    if ($zeile =~ m/^\s*$/ ) ...
    if ($zeile =~ m/^Subject: (.*)/ ) ...
    if ($zeile =~ m/^Date: (.*)/ ) ...
    if ($zeile =~ m/^Reply-To: (\S+)/ ) ...
    if ($zeile =~ m/^From: (\S+) \(([^()]*)\)/ ) ...
        .
        .
        .
}

Each regex must first be checked and compiled internally, after which it can search many strings. Keeping the compiled form in a cache for reuse on each iteration saves time at the cost of memory.

How this works depends on the language's regex model. Under Maintaining regular expressions we distinguished three approaches: integrated, procedural and object-oriented.

 

Caching with integrated regexes

With integrated regexes, as in Perl or awk , caching is easy: each regex is tied to a program location and reuses the compiled code from its first invocation. This is efficient but retains memory for compiled regexes.

Variable interpolation complicates caching. With m/^Subject:●\Q$GesuchterBetreff\E\s*$/, the regex may change each iteration and require recompilation every time.

It need not change, however. Save the interpolated source with its compiled form and compare before recompiling. No savings if it always changes, but considerable savings when changes are rare.

 

DFAs, Tcl, and regex tuning

Most optimizations here do not concern DFAs. Compilation caching works for every engine, but later tuning techniques do not apply to DFAs. Under How regex engines work (see Implications for users) we saw that logically equivalent expressions such as ˹klipp|klar˼ and ˹kl(ipp|ar)˼ are genuinely equivalent for DFAs. This chapter exists because they generally are not equivalent for NFAs.

What about Tcl's hybrid DFA/NFA engine? Henry Spencer, the regex pioneer (see Henry Spencer’s regex package), built it specifically for Tcl, successfully combining both engines' strengths. In an April 2000 Usenet post, he wrote:

Tcl's RE engine generally depends much less on exact RE syntax than traditional engines. Fast operations remain fast however expressed, and slow operations remain slow. The old advice about hand-optimized regexes simply no longer applies.

Henry's regex engine in Tcl is a major advance. Wider adoption could make most of this chapter unnecessary.

 

Caching with procedural interfaces

Integrated regexes are tied to program locations. A procedural function instead receives a regex without knowing its caller's context, theoretically recompiling each time. For efficiency it usually caches recently used regexes and compiled forms.

Each call searches the cache, reuses a compiled form if found, or compiles and inserts it otherwise. A full bounded cache first discards its oldest entry.

GNU Emacs caches 20 entries, Tcl 30, and PHP over 4,000. .NET normally caches 15, configurable or disableable (see Regex caching).

Cache size matters when loops use several regexes. Ideally all fit, or the first may be evicted before the next iteration.

Caching with object-oriented interfaces

With objects, programmers decide when to compile, using constructors and methods such as New Regex (.NET), re.compile (Python) and Pattern.compile (java.util.regex).

The introductory examples under Features and dialects compiled immediately before use, but could do so earlier, before a loop or during initialization, as in the benchmarks Java benchmarks, VB.NET benchmarks and Python benchmarks.

Object-oriented programmers also control disposal of compiled objects with destructors, saving memory.

 

Searching for characters or fixed substrings

Finding particular characters or substrings is cheaper than running a full NFA. Some systems therefore check whether a match must contain such text and search for it first.

For example, ˹^Subject:●(.*)˼ requires the substring ›Subject:●‹ in every match. A fast algorithm like Boyer-Moore finds it, increasingly effective for longer substrings. Simpler algorithms can seek individual characters too, preferably rare ones: ›t‹ in the ›Subject:●‹ example is more common than ›:‹, potentially saving time.

An engine easily identifies regex parts such as ˹^Subject:●(.*)˼, containing fixed strings required in every match. But detecting that ˹klipp|klar|eklig˼ contains ›kl‹ in every branch is harder. Most implementations miss this, though some identify required individual characters such as ›l‹ and ›k‹.

Systems implement fixed-string optimization differently; alternation often blocks it. Factoring ˹klipp|klar˼ into ˹kl(ipp|ar)˼ helps. See also the related First-character optimization.

 

Minimum-length checking

The regex ˹^Subject:●(.*)˼ may match arbitrarily long text, but requires at least nine characters, allowing shorter subjects to be skipped. Longer minima improve this optimization: ˹:\d{79}:˼ requires at least 81 characters. See also Length checking by the transmission.

  

 

 

 

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