Re: why a.pl is faster than b.pl



Jeff Pang wrote:
> I have two perl scripts as following:
>
> a.pl:
> ----
> #!/usr/bin/perl
> use strict;
>
> my @logs = glob "~/logs/rcptstat/da2005_12_28/da.127.0.0.1.*";
>
> foreach my $log (@logs) {
> open (HD,$log) or die "$!";
> while(<HD>){
>
> if (
> ($_ =~ /×¢²á/o) ||
> ($_ =~ /Õ÷ÎÄ/o) ||
> ($_ =~ /Ê¥µ®¿ìÀÖ/) ||
> ($_ =~ /ӦƸ/o) ||
> ($_ =~ /Íøͨ/o) ||
> ($_ =~ /·¢»õ/o) ||
> ($_ =~ /±±¾©/o) ||
> ($_ =~ /×ÊÁÏ/o) ||
> ($_ =~ /ÐÅÏ¢/o) ||
> ($_ =~ /Ïãɽ/o) ||
> ($_ =~ /°ÙÍò/o) ||
> ($_ =~ /Ãâ·Ñ/o) ) {
> print $_;
> }
> }
> close HD;
> }
>
>
> b.pl
> ----
> #!/usr/bin/perl
> use strict;
>
> my $ref = sub { $_[0] =~ /×¢²á/o || $_[0] =~ /Õ÷ÎÄ/o || $_[0] =~ /Ê¥µ®¿ìÀÖ/o ||
> $_[0] =~ /ӦƸ/o || $_[0] =~ /Íøͨ/o || $_[0] =~ /·¢»õ/o ||
> $_[0] =~ /±±¾©/o || $_[0] =~ /×ÊÁÏ/o || $_[0] =~ /ÐÅÏ¢/o ||
> $_[0] =~ /Ïãɽ/o || $_[0] =~ /°ÙÍò/o || $_[0] =~ /Ãâ·Ñ/o };
>
>
> my @logs = glob "~/logs/rcptstat/da2005_12_28/da.127.0.0.1.*";
>
> foreach my $log (@logs) {
> open (HD,$log) or die "$!";
> while(<HD>){
> print if $ref->($_);
> }
> close HD;
> }
>
>
> I run the 'time' command to get the running speed:
>
> time perl a.pl > /dev/null
>
> real 0m0.190s
> user 0m0.181s
> sys 0m0.008s
>
>
> time perl b.pl > /dev/null
>
> real 0m0.286s
> user 0m0.278s
> sys 0m0.007s
>
>
> Why the a.pl is faster than b.pl? I think ever the resulte should be opposite.Thanks.

Can you explain why you believe b.pl should be faster? From looking at
your code, I see that b.pl has to do the following extra work:
1) Dereference a subroutine reference for every iteration of the while
loop
2) Call a subroutine for every iteration of the while loop
3) Retrieve the first element of @_ for every pattern match for every
iteration of the while loop (retrieving an element from an array is
more work than retrieving a simple scalar)

If you're really curious about what pieces of your code take what
amounts of time, allow me to suggest looking into the Devel::DProf
module, which is a core module:

perldoc Devel::DProf

Paul Lalli

.