in reply to Speed comparison of foreach vs grep + map
As Corion pointed out, the switch from !$_ to /0/ is overpowering the other differences and invalidating your test.
But other improvements can be made.
There's no reason to use an intermediate array in the latter snippet. This avoids the creation of 5 million scalars.
my @e = grep !$_, map $_ % 2, @c;
You could even eliminate the grep.
my @e = map $_ % 2 ? () : 0, @c;
Similar improvements can be made for the foreach version.
my @e; for my $c ( @c ) { my $d = $c % 2; push @e, $d if !$d; }
my @e; for my $c ( @c ) { push @e, 0 if !( $c % 2 ); }
Finally, I'm curious how these compare:
my @e = ( 0 ) x grep !( $_ % 2 ), @c;
my @e; push @e, 0 for 1 .. grep !( $_ % 2 ), @c;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Speed comparison of foreach vs grep + map
by ikegami (Patriarch) on May 29, 2025 at 16:48 UTC |