I've noticed a huge (10x) performance difference between two algorithims. It's not obvious (to me) why the difference is so great. I'm trying to parse each line of a file that's already been read into an array. There are three different lines that are interesting. They are in the @patterns array. I have an outer loop to iterate over the source lines and an inner loop to iterate over the patterns. I store the interesting lines in another array. With a particular data set this code takes around 30 seconds to execute.
my @patterns = ("SDC: HUT time changed: 0", "BATT: Cap=0\\(watt-min\\) HUT=0\\(min\\) 0\\(hrs\ +\) state=GOOD->BAD", "BATT: Log battery system condition GOOD->BAD"); my @events; foreach my $line (@$srcRef) { foreach my $pattern (@patterns) { if ($line =~ /$pattern/) { push(@events, $line); last; } } }
Unrolling the inner loop like so, results in 3 second execution and appears to produce the same results. Why the 10x hit with the nested loops? What am I missing? Thanks.
foreach my $line (@$srcRef) { if ($line =~ /SDC: HUT time changed: 0/) { push(@events, $line); } elsif ($line =~ /BATT: Cap=0\(watt-min\) HUT=0\(min\) 0\(hrs\) + state=GOOD->BAD/) { push(@events, $line); } elsif ($line =~ /BATT: Log battery system condition GOOD->BAD/ +) { push(@events, $line); } }

In reply to performance explanation needed by yoganaut

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.