why the for loop version use much less memory?

for (x..y) loop and for (@array) loop (but no other kind of for (LIST) loops) are optimized to iterate over the list without flattening it.

$n = 10_000_000; print ": "; <>; # 2MB $f = 1; for (0..$n-1) { if ($f) { $f = 0; print ": "; <>; } } # 2MB
$n = 10_000_000; print ": "; <>; # 2MB push @a, --$n while $n; print ": "; <>; # 240MB $f = 1; for (@a) { if ($f) { $f = 0; print ": "; <>; } } # 240MB

grep { ... } LIST flattens the list, so grep { ... } @array loads the entire array* on the stack and grep { ... } 0..$#array; create a list in memory as big as the array.

$n = 10_000_000; print ": "; <>; # 2MB $f = 1; grep { if ($f) { $f = 0; print ": "; <>; } 0 } 0..$n-1; # 240MB <--
$n = 10_000_000; print ": "; <>; # 2MB push @a, --$n while $n; print ": "; <>; # 240MB $f = 1; grep { if ($f) { $f = 0; print ": "; <>; } 0 } @a; # 280MB <--

* - The amount of memory taken is proportional to the number of elements. It doesn't matter how much memory each of those element takes.

Also, will the use of direct access the array index make the grep slower?

I don't completely understand what you said, but the answer is clear: Write a Benchmark test to find out.

Updated: Added code snippets.


In reply to Re^3: grep return the index instead of the element content, and its speed by ikegami
in thread grep return the index instead of the element content, and its speed by Anonymous Monk

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.