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


in reply to Re: map {} list or do {} for list? - Benchmarks
in thread map {} list or do {} for list?

When you see operations per second that high, you should ask yourself if any work is being done. In fact, none really is, and your benchmark is rendered totally unreliable as a result. First, you have scoping issues. And even if you fix those, you remain with the issue that choroba identified; that the first benchmark iteration deletes from the master copy of the hash, leaving remaining iterations with less work to do.

Here's a version that codes around the scoping issues that evaled code creates, and that makes a copy of %hosts on each iteration. That copy costs time, but it costs the same amount of time for each snippet.

use Benchmark qw(cmpthese); our $t_count = 3; our %hosts = map { $_ => $t_count - ( rand 50 > 49 ? 1 : 0 ) } (1 .. +1000); my $count = 10000; cmpthese($count, { do => 'my %t = %main::hosts; do { delete $t{$_} unless $t{$_} == +$main::t_count } for keys %t;', map => 'my %t = %main::hosts; map { delete $t{$_} unless $t{$_} == + $main::t_count } keys %t;', or => 'my %t = %main::hosts; $t{$_} == $main::t_count or delete $ +t{$_} for keys %t;', slice => 'my %t = %main::hosts; delete @t{ grep { $t{$_} != $main::t +_count } keys %t };', copy => 'my %t = %main::hosts; %t = map { $t{$_} == $main::t_count +? ($_, $t{$_}) : ()} keys %t;', nada => 'my %t = %main::hosts;' });

And here's the output I get:

Rate copy map or do slice nada copy 1372/s -- -57% -57% -57% -58% -78% map 3175/s 131% -- -2% -2% -2% -50% or 3226/s 135% 2% -- 0% -0% -49% do 3226/s 135% 2% 0% -- -0% -49% slice 3236/s 136% 2% 0% 0% -- -49% nada 6289/s 358% 98% 95% 95% 94% --

"nada" is just there to identify how much time we're wasting making a fresh copy of the hash on each iteration.

As you can see, all of the approaches except for the copy one are so close that they're probably within the margin of error. Use the one that seems most legible, and if there's a risk that it won't be comprehended, encapsulate by wrapping it in a well-named subroutine.


Dave