It's faster, but not because the pattern itself is faster. You're getting the benefit because your regexp isn't changing, and you're doing the same pattern tens of thousands of times. The loop I suggested doesn't have that benefit.
But it can.
use strict;
use warnings;
use 5.010;
use Benchmark qw[ cmpthese ];
use List::Util qw[ shuffle ];
our @terms = qw[
the quick brown fox jumps over the lazy dog
];
our $re = join'', map "(?=^.*$_)", @terms;
$re = qr/$re/;
our @lines = map join( ' ', shuffle @terms), 1 .. 100;
push @lines, ( 'every good boy deserves food' ) x 100;
my $line = join '&&', map {"/$_/"} @terms;
our( $a, $b, $c ) = (0) x 3;
cmpthese -1, {
a=>q[ /$re/ and ++$a for @lines; ],
b=>q[ for my $str ( @lines ) { !grep( $str !~ /$_/, @terms) and ++
+$b; } ],
c=>qq [$line && ++\$c for \@lines;],
};
say "$a:$b:$c";
__END__
Rate b a c
b 39.8/s -- -95% -97%
a 807/s 1927% -- -36%
c 1254/s 3051% 55% --
109400:4800:243000
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.