XML technologies / Regular expressions / Perl / Efficiency in Perl / Perl copies the subject before matching

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

Matching or substitution sometimes makes Perl copy the subject at significant cost. Certain regex variables require it, but some copies are unnecessary. For long subjects and speed-sensitive programs, avoid needless copying.

The following sections explain why copying happens, how the copy is used, and how to avoid it.

 

The subject copy supports $1, $&, $', $+, etc.

Before matching or substitution, Perl copies the subject to support $1, $& and other variables containing subject text (see Special variables controlled by matching). Rather than creating substrings, Perl stores for $1 and others references to start and end positions within the copy. This reduces work during matching, helpful since these variables often go unused. It is a form of lazy evaluation, avoiding unnecessary work.

But why copy first instead of referencing the original? Consider:

$Subject =~ s/^(?:Re:\s*)+//;

After this substitution, $& refers to text removed from $Subject, but that text is now deleted. References would be invalid, so Perl cannot use $Subject when $& is later accessed. Likewise:

if ($Subject =~ m/^SPAM:(.+)/i) {
    $Subject = "-- Spam entfernt --";
    $SpamAnzahl{$1}++;
}

By the time $1 is evaluated, $Subject has been overwritten. A copy is needed for $1 to work.

 

The copy is not always needed

Usually the copy serves $1, $2, $3 and similar variables. Without capturing parentheses, they cannot be set. Can we then omit the copy? Not always…

 

The variables $`, $& and $' are “naughty”

The three variables $`, $& and $' do not depend on captures. every match and every substitution has matched, preceding, and following text. Perl cannot easily determine which regex the variables reference, so copying happens every time.

Copying seems inevitable, but Perl detects that in the entire program, including libraries, nowhere are any of $`, $& or $' used. If absent, Perl can avoid copying. Ensuring your code and every module never uses $`, $&, or $' permits this substantial optimization! A single occurrence of $`, $& or $' anywhere defeats the optimization, hence my name “naughty.”

 

How expensive is copying?

I benchmarked m/c/ over roughly 130,000 lines of Perl source, checking for ›c‹ without using the result. I compared runs with copying disabled and forced; differences are solely copying costs.

Copying took over 40% longer, an average bad case. Other program work dilutes the impact; this benchmark does nothing else, exaggerating it.

In a catastrophic case, copying dominates. I retested the same data as one single line over 3.5 MB rather than 130,000 normal lines. Without copying, finding the first ›c‹ was nearly instant; copying the huge line made it over 7,000 times slower. Knowing this helps programming decisions.

 

Avoiding subject copying

Ideally Perl would copy only when truly needed. Copying is not inherently bad: handling such details is why we choose Perl over C or assembly, leaving us free to solve problems.

 

Avoid naughty variables

Still, avoid needless work. Prefer to completely avoid $`, $& and $' . Often replace $& by capturing the entire regex and using $1. To lowercase HTML tags, replace s/<\w+>/\L$&\E/g with s/(<\w+>)/\L$1\E/g.

If the subject is unchanged, $` and $' can often be replaced by substr(). After success in the subject , use these replacements:

Variable

Replacement using substr

$`

substr(Suchstring, 0, $-[0])

$&

substr(Suchstring, $-[0], $+[0] - $-[0])

$'

substr(Suchstring, $+[0])

The arrays @- and @+ (see @- and @+) contain positions into the original subject, not copied text, and are safe to use.

I also give a replacement for $&, potentially faster than capturing with $1 if it avoids capturing groups entirely. Replacing $& aimed to avoid copying for capture-free regexes. Removing $& but adding captures everywhere gains nothing.

 

Checking programs for $& contamination

Detecting use of $&, $` or $' can be hard, especially inside modules. With a Perl interpreter compiled using -DDEBUGGING , invoke Perl with -c and -Mre=debug (see Regex debugging information) and inspect debug output for ›Enabling $` $& $' support‹ or ›Omitting $` $& $' support‹. “Enabling” means contamination.

A naughty variable may rarely appear in eval and be detected only when that eval code runs. The module Devel::SawAmpersand can detect this and is available on CPAN:

END {
   require Devel::SawAmpersand;
   print "Unartige Variablen!\n" if Devel::SawAmpersand::sawampersand;
}

Devel::SawAmpersand also contains Devel::FindAmpersand, which should locate the variable, but is unreliable in recent Perl versions. Both modules are also difficult to install.

Alternatively, test at runtime whether the slowdown occurs:

use Time::HiRes;
sub Knigge() {                 # Test auf Gutartigkeit.
   my $text = 'x' x 10_000;    # Nicht-triviale Datenmenge.

   # Zeit für die leere Schleife ermitteln.
   my $start = Time::HiRes::time();
   for (my $i = 0; $i < 5_000; $i++)  {  }
   my $leer = Time::HiRes::time() - $start;

   # Zeit für die gleiche Anzahl einfacher Matchings ermitteln.
   $start = Time::HiRes::time();
   for (my $i = 0; $i < 5_000; $i++)  { $text =~ m/^/  }
   my $delta = Time::HiRes::time() - $start;
  
   # Faktor 5 ist nur Pi mal Daumen.
   printf "Ihr Programm ist %s (Leerschleife=%.2f, Delta=%.2f)\n",
      ($delta > $leer*5) ? "unartig" : "brav", $leer, $delta;
}

 

Avoid naughty modules

$`, $& and $' should be avoided; this also means avoiding libraries using them. Among bundled modules only English uses them, and it can be loaded without them:

use English '-no_match_vars';

This makes it safe, without long aliases for those variables, which we do not want anyway. For other modules, consider testing whether they use $`, $& or $' using the method above.

  

 

 

 

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