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% --

In reply to Re^2: Deleting records from an array by Anonymous Monk
in thread Deleting records from an array by viffer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.