in reply to Re: Battle Royal Grep vs For
in thread Battle Royal Grep vs For

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

Replies are listed 'Best First'.
Re^3: Battle Royal Grep vs For
by Fletch (Bishop) on Mar 19, 2008 at 17:54 UTC

    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!