I was writing up an example of using mmap last night in Re: anyone have some good mmap examples?, and was surprised at how poorly my first version performed. It essentially mmaped in a fairly large file, then tried to match lines containing a pattern with:
while ($mmap =~ m/^([^\n]*$pat[^\n]\n)/omg) { print $1; }

I found performance was abysmal: 20 seconds to search a 400K file (/usr/share/dict/words) for "foo". Some investigation (and perl -Dr) revealed that the regex engine was finding "foo" in the string very quickly, then was trying every single line preceding it to see if it matched against the remaining regex. I rewrote my simple pattern to:

while ($mmap =~ m/$pat/omg) { my $pos = pos $mmap; # Find the beginning and end of this line my $first = rindex($mmap,"\n",$pos)+1; my $last = index($mmap,"\n",$pos)+1; print substr($mmap,$first,$last-$first); }
and runtime went from 20 seconds to .040 seconds.

My question is: is there anything I could have told Perl to give it a hint about how to perform the match, such as "Hey Perl, the ^ is going to be pretty close to $pat, so just search backwards from wherever you find it"?

Here's a full copy of the original program.

#!/usr/bin/perl use warnings; use strict; use Sys::Mmap; our $pat = shift; foreach my $a (@ARGV) { my $mmap; if (! -f $a) { warn "'$a' is not a regular file, skipping\n"; next; } open(F, "< $a") or die "Couldn't open '$a': $!\n"; mmap($mmap, 0, PROT_READ, MAP_SHARED, F) or die "mmap error: $!\n"; while ($mmap =~ m/^([^\n]*$pat[^\n]\n)/omg) { print $1; } munmap($mmap) or die "mmunmap error: $!\n"; close(F) or die "Couldn't close '$a': $!\n"; }

In reply to Surprisingly poor regex performance by sgifford

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.