in reply to Re: Deleting records from an array
in thread Deleting records from an array

Also, it's very efficient.
I was curious about that and decided to test it. Splice is more efficient then I thought but it's still not as fast as undef with big arrays.
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, } );
So with arrays of 1000 element they're equal:
x $ perl cmp.pl -t 1000 -s 1000 Rate splice undef splice 287/s -- -3% undef 296/s 3% --
10000 elements and undef becomes a bit faster:
$ perl cmp.pl -t 1000 -s 10000 Rate splice undef splice 19.4/s -- -21% undef 24.7/s 27% --
40000 elements and undef significantly faster:
$ perl cmp.pl -t 100 -s 40000 Rate splice undef splice 2.41/s -- -43% undef 4.24/s 76% --
Even with the most favorable conditions for splice they're about equal:
$ perl cmp.pl -t 1000000 -s 10 Rate splice undef splice 18678/s -- -7% undef 20190/s 8% --