in reply to Re: Quicly extracting odd index elements in the array with grep
in thread Quicly extracting odd index elements in the array with grep
and it's faster for not having to generate an extra array:
use warnings; use strict; use Benchmark qw(cmpthese); my @arr = (0,3,4,5,8,10,12,15, 1..999999); cmpthese (-2, { mapgrep => sub {map {$arr[$_]} grep {$_ & 1} 1..$#arr}, slice => sub {@arr[ grep {$_ & 1} 1..$#arr ];}, grep => sub {my $ind = 0; grep {$ind++ % 2} @arr}, push => sub {my @var; push(@var, $arr[$_*2+1]) for 0..int(@arr +/2)-1}, map => sub {map { $arr[$_*2+1] } 0..int(@arr/2)-1}, } );
Prints:
# my @arr = (0,3,4,5,8,10,12,15, 1..999999); Rate mapgrep slice push map grep mapgrep 2.02/s -- -29% -35% -38% -40% slice 2.84/s 40% -- -9% -13% -16% push 3.11/s 54% 9% -- -5% -8% map 3.27/s 62% 15% 5% -- -3% grep 3.37/s 66% 18% 8% 3% -- # my @arr = (0,3,4,5,8,10,12,15); Rate push mapgrep slice map grep push 160309/s -- -30% -39% -50% -54% mapgrep 229948/s 43% -- -12% -28% -34% slice 261705/s 63% 14% -- -18% -25% map 319334/s 99% 39% 22% -- -9% grep 350258/s 118% 52% 34% 10% --
The performance holds pretty much regardless of size.
Update: more cases added
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Quicly extracting odd index elements in the array with grep
by ssandv (Hermit) on Dec 09, 2009 at 18:54 UTC |