That is jumping through some hoops to avoid void. SuprisinglyUnsuprisingly (I just looked at it properly) the first one is a lot slower than the map in void context solution, the last one is slowest of all :)
Updated
added the for loop solution to the benchmark, it is nicely faster.
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark;
my @strings;
my @array;
push @strings, $_ x 2 for ("a" .. "z");
for (1..1000) {
my $i=int rand $#strings;
push @array, $strings[$i]
}
sub for_loop {
my %sums;
$sums{$_}++ foreach @array;
# print "$_ = $sums{$_}\n" foreach sort keys %sums;
}
sub map_void {
my %sums;
map {$sums{$_}++} @array;
# print "$_ = $sums{$_}\n" foreach sort keys %sums;
}
sub nonvoid_1 {
my %sums;
%sums = map {$_ => ++$sums{$_} } @array;
# print "$_ = $sums{$_}\n" foreach sort keys %sums;
}
sub nonvoid_2 {
my %sums;
my $last="";
%sums = map {
my $n;
do { $n = (($last=$_) ... ($last ne $_)) } while $n =~ /E0$/;
($last => $n);
} sort @array;
# print "$_ = $sums{$_}\n" foreach sort keys %sums;
}
timethese( -3, {map_void => \&map_void,
for_loop => \&for_loop,
nonvoid_1 => \&nonvoid_1,
nonvoid_2 => \&nonvoid_2 }
);
__END__
Benchmark: running for_loop, map_void, nonvoid_1, nonvoid_2 for at lea
+st 3 CPU seconds...
for_loop: 3 wallclock secs ( 3.13 usr + 0.01 sys = 3.14 CPU) @ 15
+79.94/s (n=4961)
map_void: 3 wallclock secs ( 3.19 usr + 0.00 sys = 3.19 CPU) @ 11
+65.83/s (n=3719)
nonvoid_1: 3 wallclock secs ( 3.16 usr + 0.00 sys = 3.16 CPU) @ 33
+0.06/s (n=1043)
nonvoid_2: 3 wallclock secs ( 3.28 usr + 0.00 sys = 3.28 CPU) @ 13
+9.33/s (n=457)
Cheers, R.
Pereant, qui ante nos nostra dixerunt!
|