I did a little, very basic, test, and I find the result quite interesting (and also confusing):
#!/usr/bin/perl use Benchmark; timethese(10000, { 'foreachmy' => sub { my ($sum,$avg); foreach my $i (1..1000) { $sum += $i; $avg = $sum/$i; } }, 'foreachglobal' => sub { my ($sum,$avg,$i); foreach $i (1..1000) { $sum += $i; $avg = $sum/$i; } }, 'foreachnovar' => sub { my ($sum,$avg); foreach (1..1000) { $sum += $_; $avg = $sum/$_; } }, 'fornovar' => sub { my ($sum,$avg); for (1..1000) { $sum += $_; $avg = $sum/$_; } }, 'ctypeFor' => sub { my ($i,$sum,$avg); for ($i=1;$i<=1000;$i++) { $sum += $i; $avg = $sum/$i; } } } );
Benchmark: timing 10000 iterations of ctypeFor, foreachglobal, foreach +my, foreachnovar, fornovar... ctypeFor: 26 wallclock secs (26.27 usr + 0.00 sys = 26.27 CPU) foreachglobal: 22 wallclock secs (22.50 usr + 0.00 sys = 22.50 CPU) foreachmy: 23 wallclock secs (22.42 usr + 0.00 sys = 22.42 CPU) foreachnovar: 23 wallclock secs (23.33 usr + 0.00 sys = 23.33 CPU) fornovar: 24 wallclock secs (23.44 usr + 0.03 sys = 23.47 CPU)
While I'm not so sure about the little difference between the foreachlocal and foreachmy result, the construct foreach local $i (.....) definitely seems to be faster than foreach (......) ... or am I doing something terrible to $_ IN the foreach block?

In reply to Re: List processing performance by vijeno
in thread List processing performance by Odud

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.