Thank you for the replies everyone! I've put all the solutions together here - I've kept the behavior of deleting only a single value, but the comparison with deleting multiple indicies by choroba here is very interesting too! I've included Eily's solution that leaves the array out of its original order too.
use warnings; use strict; use Benchmark qw/cmpthese/; my @numbers = ( 'a'..'t' ); my $index = 3; my $expect = 'abcefghijklmnopqrst'; use constant TEST => 0; cmpthese(-2, { splice => sub { my @output = @numbers; splice @output, $index, 1; join("", @output) eq $expect or die if TEST; }, grep => sub { # choroba my @output = @numbers[ grep $_ != $index, 0 .. $#numbers ]; join("", @output) eq $expect or die if TEST; }, slice => sub { # hippo my @output = @numbers[ 0..$index-1, $index+1..$#numbers ]; join("", @output) eq $expect or die if TEST; }, hash => sub { # bliako my %ha; @ha{0..$#numbers} = @numbers; delete $ha{$index}; my @output = map { $ha{$_} } sort {$a <=> $b} keys %ha; join("", @output) eq $expect or die if TEST; }, hash_slice => sub { # swl my %ha; @ha{0..$#numbers} = @numbers; delete $ha{$index}; my @output = @ha{ sort {$a <=> $b} keys %ha }; join("", @output) eq $expect or die if TEST; }, swap => sub { # Eily my @output = @numbers; $output[$index] = pop @output; join("", sort @output) eq $expect or die if TEST; }, pop_sort => sub { # Eily's + sort my @output = @numbers; $output[$index] = pop @output; @output = sort @output; join("", @output) eq $expect or die if TEST; }, }); __END__ Rate hash hash_slice grep pop_sort slice sw +ap splice hash 113253/s -- -10% -78% -82% -84% -8 +7% -87% hash_slice 126029/s 11% -- -76% -80% -83% -8 +5% -86% grep 518838/s 358% 312% -- -17% -28% -3 +9% -41% pop_sort 627138/s 454% 398% 21% -- -14% -2 +6% -28% slice 725216/s 540% 475% 40% 16% -- -1 +4% -17% swap 846179/s 647% 571% 63% 35% 17% +-- -3% splice 873809/s 672% 593% 68% 39% 20% +3% --
In reply to Re: Fastest way to "pick without replacement"
by haukex
in thread Fastest way to "pick without replacement"
by haukex
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |