If the memory use issue is due to thousands of small arrays quadrupling in size, then my solution could be useful.

My point was that it's only useful if it's required for the original arrays to remain unchanged.

I could splice @c (or @a) in the foreach,

That would be extremely slow [ probably O(N2) ] compared to the following [ O(N) ]:

# @c = grep !defined, @c; # is O(N) speed, O(N) memory. # # The following does the same, but # is O(N) speed, O(1) memory. my $last = -1; my $i = -1; while (++$i < @c) { if (defined($c[$i]) { $c[++$last] = $c[$i]; } } $#c = $last;

If the last line isn't O(1) memory, replace it with

pop @c while $#c > $last;

BTW, why do you use a for loop to push the elements of @a onto @c? Why not push @c, @a; instead?

push uses O(N) memory (where N is the number of elements pushed).
for ARRAY (as opposed to for LIST) is optimized to use O(1) memory, I think.


In reply to Re^4: Difference arrays. by ikegami
in thread Difference arrays. by BrowserUk

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.