The simple case in both examples was the correct and faster version. In the first example the list 1 .. 100 didn't have to created all at once and was represented internally as an iterator. Putting the grep() on that required that perl create all of 1 .. 100 first and then loop over that list.

In your second question the first case has perl doing a loop on an array which is fast and efficient. Your second case involves a continue block, indexed access and reference lookups. Just for your own edification, run these four perl commands and compare the output to each other.

perl -MO=Concise -e 'for(1 .. 100){print if $_ < 50}' perl -MO=Concise -e 'for(grep $_ < 50, (1 .. 100)){print}' You'll notice that you've just traded an "and" and a few constants for + that larger grep. leaveloop enteriter pushmark - const - const + grepwhile + grepstart + pushmark + lt + gvsv + const + rv2av + const gv and iter lineseq nextstate - and - lt - gvsv - const - print - pushmark - gvsv + print + pushmark + gvsv unstack nextstate perl -MO=Concise -e '$array_ref=[1..10000];for(@$array_ref){print}' perl -MO=Concise -e '$array_ref=[1..10000];for($i=0;$_=$array_ref->[$i +];$i++){print}' Here you'll notice that you you doubled the number of operations being + performed for handling the first construct. Ugly. nextstate - leaveloop - enteriter - pushmark - rv2av - rv2sv - gv - gv - and - iter - lineseq - nextstate - print - pushmark + sassign + const + gvsv + lineseq + nextstate + leaveloop + enterloop + and + sassign + aelem + rv2av + rv2sv + gv + gvsv gvsv - unstack - nextstate + lineseq + scope + print + pushmark + gvsv + preinc + gvsv + unstack + nextstate

In reply to Re: Loops, lists and efficiency by diotalevi
in thread Loops, lists and efficiency by Arunbear

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.