in reply to perl performance vs egrep

Would it give a speed improvement to prepare the regex in advance with qr//?

my $re = qr/^CPXX1|^KLXX1|^KMXX1|^MEXX1|^PAXX1|^PMXX1|^SLXX1|^SZXX1|^WXXX1|^YZXX1/;
...
print OFILE unless /$re/;
...

I think other monks have already suggested using a buffer to reduce the number of write, this would probably give a fairly major improvement.

Replies are listed 'Best First'.
Re^2: perl performance vs egrep
by holli (Abbot) on Jan 23, 2005 at 17:56 UTC
    Would it give a speed improvement to prepare the regex in advance with qr//?
    No, it wouldn´t. At least not as long the regex is, like here, the only one within the loop. The qr//-operator is useful when you have the need of matching the same string to multiple regexes/patterns, like in
    @p = ( qr/^abc/, qr/abc$/, ); for $f ( @foo ) { for $p ( @p ) { do_stuff() if $f =~ $p; } }
    Using qr// doesn´t even help in code like
    while ( $foo =~ /^abc/ && $foo =~ /abc$/ ) { do_stuff(); }
    because in such a case internal perl optimizations come into play.

    holli, regexed monk
Re^2: perl performance vs egrep
by Tanktalus (Canon) on Jan 23, 2005 at 17:55 UTC

    Probably not. The perl compiler should be able to see that the entire regexp is completely, 100% static, and no variables in it whatsoever. Thus, it should compile the regexp once (ideally on first call, but I suspect it's done during compilation) regardless. All you're doing is copying that compiled regexp around a bit. Should have practically no effect.