use 5.020;
use warnings;
use Benchmark qw( cmpthese );
use Getopt::Long;
my ( $times, $size ) = ( 1_000, 1_000 );
GetOptions(
'times=i' => \$times,
'size=i' => \$size,
);
my @keys = 'a' .. 'z';
my @vals = map $keys[ rand @keys ], 1 .. $size;
sub with_undef {
my @needles = @keys;
my @haystack = @vals;
for my $needle (@needles) {
for my $elem (@haystack) {
next if not defined $elem;
if ( $elem eq $needle ) {
$elem = undef;
}
}
}
}
sub with_splice {
my @needles = @keys;
my @haystack = @vals;
for my $needle (@needles) {
for my $idx ( 0 .. $#haystack ) {
last if $idx > $#haystack;
if ( $haystack[$idx] eq $needle ) {
splice @haystack, $idx, 1;
redo;
}
}
}
}
cmpthese(
$times, {
undef => \&with_undef,
splice => \&with_splice,
}
);
####
x $ perl cmp.pl -t 1000 -s 1000
Rate splice undef
splice 287/s -- -3%
undef 296/s 3% --
####
$ perl cmp.pl -t 1000 -s 10000
Rate splice undef
splice 19.4/s -- -21%
undef 24.7/s 27% --
####
$ perl cmp.pl -t 100 -s 40000
Rate splice undef
splice 2.41/s -- -43%
undef 4.24/s 76% --
####
$ perl cmp.pl -t 1000000 -s 10
Rate splice undef
splice 18678/s -- -7%
undef 20190/s 8% --