in reply to Battle Royal Grep vs For

Your benchmark may be relatively fair, but your use of qr is bad. qr is used to compile a regex, so you are compiling a regex on every iteration of your loops. You could assign something like my $re = qr{test}; before the benchmark and then use /$re/ in the benchmark, but I think it would be better to just use /test/ inside the benchmark code, that way you're not measuring things that you don't mean to measure.

Replies are listed 'Best First'.
Re^2: Battle Royal Grep vs For
by Herkum (Parson) on Mar 19, 2008 at 17:47 UTC

    Your point is taken, so I reran the tests and got this,

    Rate grep_loop for_loop grep_loop 150375/s -- -22% for_loop 193618/s 29% --

    So now they are both faster, but grep is still slower. Than the for loop

      And as usual grep EXPR, LIST that everyone forgets about wins the race.

      #!/usr/bin/perl use strict; use warnings; my @values = qw(test test1 test2 test3); use Benchmark qw( cmpthese ); cmpthese -2, { for_loop => sub { my @matches; for (@values) { push @matches, $_ +if $_ =~ /test/ }; }, grep_loop => sub { my @matches = grep { $_ =~ /test/ } @values; + }, grep_expr => sub { my @matches = grep $_ =~ /test/, @values + }, }; __END__ Rate grep_loop for_loop grep_expr grep_loop 248507/s -- -27% -46% for_loop 338839/s 36% -- -27% grep_expr 461521/s 86% 36% --

      You owe the oracle a Battle Royale With Cheese and a tasty drink to wash it down with.

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

        I had always gotten into the habit of using {} with grep, that I did not think about dropping them.

        This was one of the reasons I started this thread, was to gain some insight and learn a new approaches to make improvements to my code.

        That was very useful bit of information, thanks!