Dear monks,
I've hit a performance issue with using | in regexes. It seems that in some (not-so-degenerated, actually) cases it loses significantly to looping over simple regexes i.e.
$str =~ /$_// for @rx is much faster than $str =~ /$rx[0]|$rx[1]|$rx[2]/, which is rather counter-intuitive. Basically, for general cases, it would mean that alterations with grouping should be avoided at all, which is a strong statement and I wouldn't like it that way.
Is this a recognized problem? Is it a problem at all? Does it look like it needs to be reported as a bug? I can't decide myself.
Here's the test code:
use strict;
use warnings;
use Benchmark qw(:all);
my $str = 'a' x 100;
my @matchwords = qw(
aol aachen aaliyah aaron abbas abbasid abbott abby abdul abe abel abel
+ard abelson
aberdeen abernathy abidjan abigail abilene abner abraham abram abrams
+absalom abuja
abyssinia abyssinian ac acadia acapulco accra acevedo achaean
);
my $q1s = join('|', map { "$_\\s*\\w+" } @matchwords );
my $q1 = qr/$q1s/;
my @q2s = map { "$_\\s*\\w+" } @matchwords;
my @q2 = map { qr/$_/ } @q2s;
my $q3s = join('|', map { "($_)\\s*\\w+" } @matchwords );
my $q3 = qr/$q3s/;
my @q4s = map { "($_)\\s*\\w+" } @matchwords;
my @q4 = map { qr/$_/ } @q4s;
timethese( 100000, {
'alternation, no grouping' => sub {
$str =~ /$q1/;
},
'loop, no grouping' => sub {
for my $qr ( @q2 ) {
$str =~ /$qr/;
}
},
'alternation, grouping' => sub {
$str =~ /$q3/;
},
'loop, grouping' => sub {
for my $qr ( @q4 ) {
$str =~ /$qr/;
}
},
});
Here's the output:
Benchmark: timing 100000 iterations ...
alternation, grouping: 12 wallclock secs (11.92 usr + 0.00 sys = 11.9
+2 CPU) @ 8389.26/s (n=100000)
alternation, no grouping: 0 wallclock secs ( 0.19 usr + 0.00 sys =
+0.19 CPU) @ 526315.79/s (n=100000)
(warning: too few iterations for a reliable count)
loop, grouping: 2 wallclock secs ( 1.33 usr + 0.00 sys = 1.33 CPU)
+@ 75187.97/s (n=100000)
loop, no grouping: 1 wallclock secs ( 1.33 usr + 0.00 sys = 1.33 CP
+U) @ 75187.97/s (n=100000)
Update: got same results on perls 5.10.1, 5.16.0, and 5.17.6
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.