XML technologies / Regular expressions / Perl / Efficiency in Perl / regex compilation, the /o modifier, qr/.../, and efficiency

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

Regex efficiency depends on what Perl must do behind the scenes after encountering a regex operator and before the regex can be applied. Exactly what happens depends on the type of regex operand. Most often it is probably a regex literal, as in m/.../ or s/.../.../ or qr/.../. For these, Perl must make preparations each time that we would prefer to avoid where possible. Let us first examine what happens, then how we might eliminate some of that work.

 

Internal steps in preparing a regex

What happens behind the scenes before a regex operand is passed to the actual regex engine was discussed in The art of writing regular expressions (see How a regular expression is applied), but Perl has a few additional peculiarities.

Perl preprocesses a regex operand in two phases:

  1. Processing regex literals. If the regex operand is a literal, it is handled as described in the section How regex literals are parsed. Among other things, this step interpolates variables.

  2. Regex compilation. The regex is examined and, if well-formed, converted to an internal representation that the engine can process directly. Invalid expressions produce an error message.

Once Perl has a compiled regex, it can apply it to the subject string.

Not every preprocessing step must be performed for every regex on every use. They certainly must be performed the first time. But when the same regex is applied repeatedly, for example in a loop or a repeatedly called function, Perl may be able to reuse earlier work. The following sections examine how and when this is possible, and how the programmer can influence it.

 

How Perl avoids regex compilation

The following sections examine two approaches Perl uses to avoid unnecessary regex recompilation: caching and recompiling only when necessary.

 

Caching

If a regex literal contains no variables requiring interpolation, Perl knows it remains unchanged between uses. Once compiled, its cached internal representation can be reused the next time. The regex is examined and compiled only once, no matter how often the program uses it. Most regexes in this book contain no interpolated variables and are therefore good candidates for this optimization.

This does not refer to variables in code patterns or dynamic regex constructs. Those are not interpolated into the regex, but are part of an unchanging piece of code that is executed. If such a construct contains my variables, one often wishes that piece of code would be reinterpreted on each call; see the warning Beware of my variables in code patterns.

This caching always applies only within a program’s runtime. Perl does not maintain a cache preserving regexes from one program invocation to the next.

 

Recompiling only when necessary

Some regex operands cannot be cached directly. For example:

my $heute = (qw<Sun Mon Tue Wed Thu Fri Sat>)[(localtime)[6]];
# $heute enthält je nach Wochentag "Mon", "Tue" usw.

while (<LOGFILE>) {
   if (m/^$heute:/i) {
       ...

The regex m/^$heute:/ requires interpolation, but because this occurs in a loop where the value of $heute does not change, interpolation always produces the same result. Recompiling the regex each time would be very inefficient. Perl therefore compares the interpolated string with that from the preceding iteration. If unchanged, the cached compiled regex can be reused; if different, recompilation is necessary. This always requires an additional string comparison, but that costs far less than compiling an entire regex.

How much difference does this really make? Quite a lot. I once benchmarked the three versions of the $HttpUrl example from Creating and using regex objects, using the version with the fully developed $HostnameRegex . These tests measured preprocessing time—interpolation, string comparison, compilation, and other overhead—not the actual regex application, which is identical in all cases.

The results are interesting. I used the version without interpolation, with the whole regex written out by hand in m/.../, as the baseline. Interpolation and string comparison take about 25 times as long when the regex remains unchanged. But the entire preprocessing process, including compilation, takes almost a thousand times as long!

To put these numbers in perspective, even the full preprocessing, a thousand times slower, takes only 0.00026 seconds on my machine. I measured 3,846 iterations per second, versus 3.7 million with the static, noninterpolated regex. Nevertheless, the savings are impressive. The following sections examine how to achieve them in other cases too.

 

The /o modifier: compile only once

Simply put, a regex literal marked with /o is examined and compiled only once, whether or not it interpolates variables. If the regex contains no variables, /o adds nothing, since noninterpolated regexes are always cached anyway. If variables must be interpolated, compilation occurs on the first use. Every later application uses the internal compiled form from the cache because of /o.

Here is the $heute example with the /o modifier:

my $heute = (qw<Sun Mon Tue Wed Thu Fri Sat>)[(localtime)[6]];
# $heute enthält je nach Wochentag "Mon", "Tue", usw.

while (<LOGFILE>) {
   if (m/^$heute:/io) {
       ...

This is much more efficient, because $heute is evaluated and interpolated only once, on the first iteration. Avoiding interpolation and string comparison on each loop iteration saves a great deal of work. Perl cannot do this on its own: the value of $heute might change, so Perl must evaluate the string each time. With the /o modifier, we tell Perl that the regex will never change after its first compilation. We can safely do so here, knowing that the variable $heute never changes throughout the loop. We can also use /o when the variable changes but we want Perl always to use its original value.

 

Possible pitfalls with the /o modifier

However, the /o modifier can also introduce bugs. Let us wrap our example in a subroutine:

sub LogdateiFuerHeute() {

   my $heute = (qw<Sun Mon Tue Wed Thu Fri Sat>)[(localtime)[6]];

   while (<LOGFILE>) {
      if (m/^$heute:/io) { # Achtung: mögliche Falle!
          ...
      }
   }
}

The /o specifies that this regex operand should be evaluated and compiled only once. The first call to LogdateiFuerHeute() caches a regex containing the current date. Later calls use this cached compiled regex even if the date, and thus $heute, has changed in the meantime.

This is a major drawback, but regex objects can help us handle it too.

 

Regex objects for improved efficiency

All our efficiency considerations so far have concerned regex literals. The goal was to examine and compile the regex only as often as strictly necessary. Instead, we can use a regex object . Regex objects are essentially ready-to-use, precompiled regexes stored in a variable. They are created with the qr/.../ operator (see The qr/.../ operator and regex objects).

Here is a version of our example using a regex object:

sub LogdateiFuerHeute()
{
   my $heute = (qw<Sun Mon Tue Wed Thu Fri Sat>)[(localtime)[6]];

   my $RegexObj = qr/^$heute:/i; # Wird einmal pro Funktionsaufruf kompiliert!

   while (<LOGFILE>) {
      if ($_ =~ $RegexObj) {
          ...
      }
   }
}

Each function call creates a new regex object, which is then used directly for every line of the log file. When a bare regex object serves as the operand, no interpolation, compilation, or other preprocessing is performed. Those steps occur earlier, when the regex object is created , not when it is used . Think of a regex object as a named cache entry you can use whenever you feel like it.

This combines the advantages of the earlier solutions: it is efficient because recompilation occurs only on each function call, rather than for every log line. Unlike the preceding solution using /o , however, it does recompile the regex when the date might have changed.

Note that this example contains two regex operands. The operand of qr/.../ is not a regex object. The qr/.../ operator creates a regex object from the literal operand. Inside the loop, that object then serves as the operand of the match operator =~.

 

Using regex objects with m/.../

A regex object can be supplied for matching like this:

if ($_ =~ $RegexObj) {

Or with the familiar slashes:

if (m/$RegexObj/) {

Although it looks like one, this is not an ordinary regex literal. If the “regex literal” consists only of a regex object, it is treated just like that object alone. This has several advantages: the notation m/.../ is conventional and familiar to most people. When using the default subject string $_, you need not specify it explicitly. Also, only this notation allows the /g modifier with a regex object.

 

The /o modifier with qr/.../

The /o modifier can be combined with qr/.../, but that makes little sense here. As with other regex operators, qr/.../o makes compilation occur only on the first execution; later executions always reuse the compiled version in the cache. In our case, $RegexObj would always contain the same regex object, even on later calls to the function LogdateiFuerHeute() and regardless of the value of $heute. We would have the same problem as the version using m/.../o above, in The /o modifier: compile only once.

 

Using the default regex to improve efficiency

The properties of the default regex (see The default for an empty regex operand) can improve efficiency, though regex objects have largely superseded this technique. I will describe it only briefly:

sub LogdateiFuerHeute() {

   my $heute = (qw<Sun Mon Tue Wed Thu Fri Sat>)[(localtime)[6]];

   # Alle Tage durchgehen, bis ein Ausdruck passt; dieser wird zur voreingestellten Regex.
   "Sun:" =~ m/^$heute:/i or
   "Mon:" =~ m/^$heute:/i or
   "Tue:" =~ m/^$heute:/i or
   "Wed:" =~ m/^$heute:/i or
   "Thu:" =~ m/^$heute:/i or
   "Fri:" =~ m/^$heute:/i or
   "Sat:" =~ m/^$heute:/i;

   while (<LOGFILE>) {
      if (m//) { # Voreingestellte Regex anwenden.
         ...
      }
   }
}

The key point is that the default regex is set only by a successful match. This example tries every weekday; one must match and thus set the default regex. This is rather roundabout, and I do not recommend it.

  

 

 

 

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