sub shuffle
{
my @in = @_;
my @out;
push @out, splice(@in, rand @in, 1) while @in;
@out;
}
####
use strict;
use Benchmark qw(cmpthese);
my @cards = 1..52;
cmpthese(-1,
{
shuffle => sub { shuffle(@cards) },
random_perm => sub { random_perm(@cards) },
});
sub random_perm {
my $n = my @p = @_;
for ( my $i = $#p; $i > 0; --$i ) {
my $j = int rand( $i + 1 );
@p[ $i, $j ] = @p[ $j, $i ];
}
return @p;
}
sub shuffle
{
my @in = @_;
my @out;
push @out, splice(@in, rand @in, 1) while @in;
@out;
}
####
Rate random_perm shuffle
random_perm 6000/s -- -30%
shuffle 8606/s 43% --