After reading Shift, Pop, Unshift and Push with Impunity!, a question occurred to me (purely academic). If I have a long array and my goal is to perform some test on each element and remove those elements that fail, what are the best ways to do it from CPU and memory standpoints? So one choice would be

@array = grep(!/^\#/, @array)

where presumably the grep operation has been heavily optimized for CPU time. However, this should create a temporary result array, which in turn could double my memory footprint. On the other extreme of the spectrum, I could say

for ( reverse 0 .. $#array) { splice (@array,$_,1) if ($array[$_] =~ /^\#/) }

but unless just about every entry is excised, that imposes a large performance toward the end of the operation. So the above-noted node inspired the following solution

for (0 .. $#array) { push @array, $value if ($value = shift @array) !~ /^\#/ }

My question is: would this ultimately have worse memory penalties than grep? It seems it must ultimately allocate enough memory at one end to accommodate the entire set, and then the interpreter/system cannot recover this memory since the variable is still allocated. Also, is there an even more clever way to do this I'm missing?

Update:Following the notes by johngg and jwkrahn, I've corrected an error in my splice loop and learned something new about negative indices. Just because you tested code doesn't mean it did what you thought...

In reply to Efficient array element deletion by kennethk

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.