in reply to Re: coderef assignment with and without eval
in thread coderef assignment with and without eval

I believe the qr// case is much faster in your benchmark because it does not involve dereferencing a coderef and then invoking a subroutine. In any case, I like the idea of using qr// so I do not need to use string eval. I thought that since qr// precompiles regexes, the subroutine using it would be just as fast as the subroutine with eval. I found that isn't the case:

#!/usr/bin/perl -w # # compiled regex with qr vs. eval and /o use strict; use Benchmark qw(timethese cmpthese); use vars qw( @words $foo $bar ); @words = qw(heaven evan seven); sub anon_sub_eval { my $pat = shift; eval 'sub { grep /$pat/o, @_ }'; } sub anon_sub_qr { my $p = shift; my $pat = qr/$p/; eval 'sub { grep /$pat/, @_ }'; } $foo = anon_sub_eval( q/evan/); $bar = anon_sub_qr ( q/evan/); my $results = timethese( -10, { anon_sub_eval => sub { $foo->(@words) }, anon_sub_qr => sub { $bar->(@words) }, } ); cmpthese($results); __END__ Benchmark: running anon_sub_eval, anon_sub_qr, each for at least 10 CP +U seconds... anon_sub_eval: 13 wallclock secs (10.73 usr + -0.01 sys = 10.72 CPU) @ + 156307.84/s (n=1675620) anon_sub_qr: 12 wallclock secs (10.40 usr + 0.01 sys = 10.41 CPU) @ 1 +36413.54/s (n=1420065) Rate anon_sub_qr anon_sub_eval anon_sub_qr 136414/s -- -13% anon_sub_eval 156308/s 15% --
Does anyone know why the qr// version is slower?

UPDATE: Thanks to a tip from suaveant, I changed the sub with qr// to not use slashes around the compiled regex:
sub anon_sub_qr { my $p = shift; my $pat = qr/$p/; eval 'sub { grep $pat, @_ }'; } __END__ Benchmark: running anon_sub_eval, anon_sub_qr, each for at least 10 CP +U seconds... anon_sub_eval: 11 wallclock secs (10.66 usr + 0.00 sys = 10.66 CPU) @ + 158363.41/s (n=1688154) anon_sub_qr: 11 wallclock secs (10.39 usr + 0.00 sys = 10.39 CPU) @ 2 +25783.45/s (n=2345890) Rate anon_sub_eval anon_sub_qr anon_sub_eval 158363/s -- -30% anon_sub_qr 225783/s 43% --
Lesson learned: do not use slashes around a regex precompiled with qr// in a grep expression. (But the difference is nominal in a regular match expression: $f =~ /$re/ vs. $f =~ $re)

--sacked