in reply to Re: Fastest way to "pick without replacement"
in thread Fastest way to "pick without replacement"
I was curious if storing the values in a hash in the first place might be better. Turns out, no, even if the output is a hash as well.
use warnings; use strict; use Benchmark qw/cmpthese/; my @array = ( 'a'..'t' ); my %hash = map { $_ => $array[$_] } 0..$#array; my $index = 3; my $expect = 'abcefghijklmnopqrst'; use constant TEST => 0; cmpthese(-2, { splice => sub { my @output = @array; splice @output, $index, 1; join("", @output) eq $expect or die if TEST; }, hash_slice => sub { my %ha; @ha{0..$#array} = @array; delete $ha{$index}; my @output = @ha{ sort {$a <=> $b} keys %ha }; join("", @output) eq $expect or die if TEST; }, swap => sub { my @output = @array; $output[$index] = pop @output; join("", sort @output) eq $expect or die if TEST; }, prehash_del => sub { my %ha = %hash; delete $ha{$index}; my @output = @ha{ sort {$a <=> $b} keys %ha }; join("", @output) eq $expect or die if TEST; }, prehash_local => sub { delete local $hash{$index}; my @output = @hash{ sort {$a <=> $b} keys %hash }; join("", @output) eq $expect or die if TEST; }, prehash_grep => sub { my @output = @hash{ sort {$a <=> $b} grep { $_ != $index } keys %hash }; join("", @output) eq $expect or die if TEST; }, outhash => sub { my %output = %hash; delete $output{$index}; join("", @output{ sort {$a <=> $b} keys %output }) eq $expect or die if TEST; }, }); __END__ Rate hash_slice prehash_del prehash_local prehash_gr +ep outhash swap splice hash_slice 127891/s -- -10% -40% -5 +0% -68% -85% -85% prehash_del 142822/s 12% -- -33% -4 +5% -64% -83% -84% prehash_local 214633/s 68% 50% -- -1 +7% -46% -75% -75% prehash_grep 258191/s 102% 81% 20% +-- -36% -70% -70% outhash 400518/s 213% 180% 87% 5 +5% -- -53% -54% swap 847448/s 563% 493% 295% 22 +8% 112% -- -2% splice 868423/s 579% 508% 305% 23 +6% 117% 2% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Fastest way to "pick without replacement"
by swl (Prior) on Nov 23, 2020 at 01:27 UTC | |
|
Re^3: Fastest way to "pick without replacement"
by LanX (Saint) on Nov 21, 2020 at 14:01 UTC | |
by haukex (Archbishop) on Nov 22, 2020 at 13:08 UTC | |
by LanX (Saint) on Nov 22, 2020 at 21:54 UTC |