in reply to Re^2: speeding up a regex
in thread speeding up a regex
In modern Perls -- I'm not sure which versions qualify here, maybe 5.6+ -- Perl will check whether the contents of the variable has changed. If the content of the variable has not changed, the regexp is not recompiled.
For example, compare
my @words = ( 'foo', 'bar', ); foreach (@array) { foreach my $word (@words) { if (/\Q$word/) { # BAD!! $word always changes. print; last; } } }
to
my @words = ( 'foo', 'bar', ); foreach my $word (@words) { foreach (@array) { if (/\Q$word/) { # GOOD!! regexp only recompiled when needed. print; last; } } }
It's not always practical to change the order of the loops. For example, when one of them reads from a file. In that case, the solution is to precompile the regexps. For example, compare
my @words = ( 'foo', 'bar', ); while (<FILE>) { foreach my $word (@words) { if (/\Q$word/) { # BAD!! $word always changes. print; last; } } }
to
my @words = ( 'foo', 'bar', ); # Precompile the regexps. my @regexps = map { qr/\Q$_/ } @words; while (<FILE>) { foreach my $regexp (@regexps) { if (/$regexps/) { # GOOD!! $regexp is a compiled regexp. #if ($_ =~ $regexp) { # GOOD!! Alternate syntax. print; last; } } }
If you're trying to match constant strings rather than regexps, then I recommend Regexp::List:
use Regexp::List (); my @words = ( 'foo', 'bar', ); my $regexp = Regexp::List->new()->list2re(@words); while (<FILE>) { print if /$regexp/; #print if $_ =~ $regexp; # Alternate syntax. }
By the way,
for ($loop_index = 0; $loop_index < $#patterns; $loop_index++) {
is much less readable and no more efficient than
for my $loop_index (0..$#patterns) {
You could also have used
foreach (@patterns) {
Finally, in your case, I'd use
my @patterns = qw( create drop delete update insert ); my $regexp; $regexp = Regexp::List->new(modifiers => 'i')->list2re(@patterns); $regexp = qr/\b(?:$regexp)\b/; ... while ($data = $sth->fetchrow_arrayref()) { # index is faster than regexps on constant strings. next if index(lc($data->[10]), 'tempdb') >= 0; if ($data->[13] =~ $regexp) { print "$data->[3] $data->[9] $data->[10] $data->[13]\n"; last; } }
Update: Bug Fix: Changed $word to $_ in map's code block.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: speeding up a regex
by sgifford (Prior) on Jan 03, 2006 at 19:59 UTC | |
by ikegami (Patriarch) on Jan 03, 2006 at 21:07 UTC | |
|
Re^4: speeding up a regex
by halley (Prior) on Jan 03, 2006 at 17:03 UTC |