Useless Benchmark!
In addition to the context issues already mentioned, your subs don't see @short, @none and @long because they are compiled in a scope where these my variables are not visible. (Put use strict; inside of the q{...} and you'll see.)
Update: The rest of this post should be ignored. To fix the above problem, change my @short to our @short, etc.
Never use q{...} with Benchmark; use sub {...} instead. It's too easy to make a scope mistake when using uncompiled code.
Fixed benchmark code:
use strict; use warnings; use Benchmark qw( cmpthese ); my @none = ('a' .. 'm' ); my @short = ('a', ''); my @long = ('a' .. 'z', ''); my $iter = shift || -3; cmpthese( $iter, { short_block_ne => sub { my @a = grep {$_ ne ''} @short; 1 }, short_block_len => sub { my @a = grep {length} @short; 1 }, short_bare_ne => sub { my @a = grep $_ ne '', @short; 1 }, short_bare_len => sub { my @a = grep length, @short; 1 }, } ); cmpthese( $iter, { none_block_ne => sub { my @a = grep {$_ ne ''} @none; 1 }, none_block_len => sub { my @a = grep {length} @none; 1 }, none_bare_ne => sub { my @a = grep $_ ne '', @none; 1 }, none_bare_len => sub { my @a = grep length, @none; 1 }, } ); cmpthese( $iter,{ long_block_ne => sub { my @a = grep {$_ ne ''} @long; 1 }, long_block_len => sub { my @a = grep {length} @long; 1 }, long_bare_ne => sub { my @a = grep $_ ne '', @long; 1 }, long_bare_len => sub { my @a = grep length, @long; 1 }, } );
Results:
Rate short_block_ne short_bare_ne short_block_len +short_bare_len short_block_ne 231725/s -- -4% -7% + -11% short_bare_ne 240180/s 4% -- -3% + -7% short_block_len 248671/s 7% 4% -- + -4% short_bare_len 259288/s 12% 8% 4% + -- Rate none_block_ne none_bare_ne none_block_len non +e_bare_len none_block_ne 55395/s -- -2% -3% + -4% none_bare_ne 56348/s 2% -- -1% + -2% none_block_len 57047/s 3% 1% -- + -1% none_bare_len 57787/s 4% 3% 1% + -- Rate long_block_ne long_bare_ne long_block_len lon +g_bare_len long_block_ne 28861/s -- -3% -4% + -8% long_bare_ne 29744/s 3% -- -2% + -5% long_block_len 30206/s 5% 2% -- + -3% long_bare_len 31265/s 8% 5% 4% + --
In reply to Re: Benchmarking the block and list forms of grep
by ikegami
in thread Benchmarking the block and list forms of grep
by grinder
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |