Update 2: The OP changed the inner while loop. This node is bunk.

What do you consider a "loop". If you are considering the outer while() to be a loop, then I would expect it to take a little while. You are iterating scalar(@list)*301*201 or over 500K times for each while.

The logic baffles me, however. Your inner loop is iterating over all of the items in @list1, and even going well beyond the end of the list, but it looks to me like you only want to loop over them with a step value of 3. Perhaps a loop like:

$indx = 0; while ($indx < $count1) { $var1 = $num1 + $list1[$indx++]; $var2 = $num2 + $list1[$indx++]; $var3 = $list1[$indx++]; # further code... }

Please note the difference between $list1[$indx...] and @list1[$indx...]. The first (my code) accesses a list element. The second (yours), if you use strict and warnings, should complain to you, and tell you to use the $list[...] form (that is, after you declare your variables with my).

Update: I just did some testing, and your code, 100 times, executes in 41.6 seconds. Mine (yes, it is doing something different, although I suspect, correct) executes in 8.3 seconds. I would also concur with the above poster that the Further code will make a huge difference.

Update2: To the original poster, please DO NOT update your original node without marking it as such, especially code sections. Your inner loop was originally  foreach(1..$count1) {...}.

--MidLifeXis


In reply to Re: faster way for multiple foreach loops by MidLifeXis
in thread faster way for multiple foreach loops by michbach

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.