Hello Monks!

I got this case of an unefficient regexp handling when matching strings in a large file:

To look for ONE string takes 2 seconds
while looking for TWO strings takes 79 seconds. Here is the code:

use strict; use Benchmark; my $file = shift || 'no_file'; timethese( 1, { 'one_string' => sub { one_string() }, 'two_string' => sub { two_string() }, } ); sub one_string { my $filter = '00901808'; my $re = qr/$filter/o; my @matched; open (my $FH, "<$file"); while (my $rec = <$FH>) { if ( $rec =~ $re) { push @matched, $rec; } } close $FH; } sub two_string { my $filter = '00901808|87654321'; my $re = qr/$filter/o; my @matched; open (my $FH, "<$file"); while (my $rec = <$FH>) { if ( $rec =~ $re) { push @matched, $rec; } } close $FH; } __END__
The result says:
# perl bench_regexp 100000lines.92MB.file Benchmark: timing 1 iterations of one_string, two_string... one_string: 2 wallclock secs ( 1.68 usr + 0.42 sys = 2.10 CPU) @ 0 +.48/s (n=1) (warning: too few iterations for a reliable count) two_string: 77 wallclock secs (76.13 usr + 0.59 sys = 76.72 CPU) @ 0 +.01/s (n=1) (warning: too few iterations for a reliable count)

pelagic

In reply to Unefficient Regexp 'Matching this or that' by pelagic

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.