in reply to Re: Regex combining /(foo|bar)/ slower than using foreach (/foo/,/bar/) ???
in thread Regex combining /(foo|bar)/ slower than using foreach (/foo/,/bar/) ???
The for and map implementations have to recompile the regex on each iteration, but the alternation doesn't have that limitation. Here's a modified version that fixes that:
use strict; use warnings; use Benchmark 'cmpthese'; undef $/; my $str = <DATA>; my @regexen = ( qr/foo/, qr/bar/ ); cmpthese(-2, { alternation => sub { my @m = $str =~ /(foo|bar)/g }, map => sub { my @m = map $str =~ /$_/g, @regexen }, loop => sub { my @m; push @m, $str =~ /$_/g for @regexe +n }, }); cmpthese(-2, { alt_s => sub { my $s2 = $str; $s2 =~ s/(foo|bar)//g }, loop_s => sub { my $s2 = $str; $s2 =~ s/$_//g for @regexen} }); __DATA__ This string contains foo and bar for fools and bards and I pity the foo who bars the way
I got results more consistant with the OP:
Rate alternation map loop alternation 26962/s -- -61% -64% map 68918/s 156% -- -9% loop 75551/s 180% 10% -- Rate alt_s loop_s alt_s 32434/s -- -20% loop_s 40707/s 26% --
Just for kicks, I added a study $str; right after reading the DATA filehandle. I know study is rarely useful, but it's supposed to help in situations where a single string is going to be matched against many different regexen, which is roughly what we have here. Results:
Rate alternation loop map alternation 26569/s -- -56% -60% loop 60015/s 126% -- -10% map 66863/s 152% 11% -- Rate alt_s loop_s alt_s 31355/s -- -19% loop_s 38857/s 24% --
The speed drops across the board, but alternation is only affected by 1.5% (which is insignificant noise). But loop gets hit hard.
"There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Regex combining /(foo|bar)/ slower than using foreach (/foo/,/bar/) ???
by kscaldef (Pilgrim) on Feb 19, 2005 at 05:45 UTC |