http://qs321.pair.com?node_id=1082078


in reply to map {} list or do {} for list?

Thanks to all who contrbuted to this thread. I have put together a quick benchmark. Unless I made an error in my code, map is the clear winner on performance grounds, as well as confusing any newbie that has to look at my code grounds ;-)

Rate or delete do copy slice map or delete 1620746/s -- -1% -50% -71% -78% do 1642036/s 1% -- -49% -70% -78% copy 3215434/s 98% 96% -- -42% -56% slice 5555556/s 243% 238% 73% -- -24% map 7299270/s 350% 345% 127% 31% --
Here is the code:
#!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); # create a hash with a few values deviating my $t_count = 3; my %hosts = map { $_ => $t_count - ( rand 50 > 49 ? 1 : 0 ) } (1 .. 1 +000); my $count = 10_000_000; cmpthese($count, { ' do' => ' do {delete $hosts{$_} unless $hosts{$_} == $t_co +unt} for keys %hosts ', ' map' => ' map {delete $hosts{$_} unless $hosts{$_} == $t_co +unt} keys %hosts ', 'or delete' => ' $hosts{$_} == $t_count or delete $hosts{$_} for k +eys %hosts ', ' slice' => ' delete @hosts{ grep { $hosts{$_} != $t_count } ke +ys %hosts } ', ' copy' => ' %hosts = map { $hosts{$_} == $t_count ? ($_, $hos +ts{$_}) : ()} keys %hosts ', });

Cheers,
R.

Pereant, qui ante nos nostra dixerunt!