I think it should also be noted that loops in general are ineffecient. Not that you should avoid them, but under certian circumstances you can optimize your code by not using one. I was a little reluctant to post this because I don't want to misdirect people to think that they should be trying to optimize away their loops. So I'll say that under very limited circumstances, you might want to consider this. Those limited circumstances would be when you notice that you have a substancial bottleneck where you're looping over a static number of elements (known at compile time).

Here's an example..

#!/usr/bin/perl -w use strict; use Benchmark; timethese(100000, { 'loop' =>'loop()', 'noloop' => 'noloop()' }); sub loop { my $x; for (1..10) { $x++; } } sub noloop { my $x; $x++; $x++; $x++; $x++; $x++; $x++; $x++; $x++; $x++; $x++; }
Results:
Benchmark: timing 100000 iterations of loop, noloop... loop: 4 wallclock secs ( 3.48 usr + 0.03 sys = 3.51 CPU) @ 28 +490.03/s ( n=100000) noloop: 0 wallclock secs ( 1.09 usr + 0.00 sys = 1.09 CPU) @ 91 +743.12/s ( n=100000)
Now in this example, the for loop works just fine, but as you can see, not using a loop is three times as fast. %99.9 of the time, you're not going to have to optimize this unless you're calling this 100k times.

Anyway, I just thought I'd throw it out there..

Rich


In reply to Re: Efficient Looping Constructs by rchiav
in thread Efficient Looping Constructs by demerphq

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.