Hello, I tried to benchmark those constructs like this:
use Benchmark qw(cmpthese); use 5.010; cmpthese(-2, { shift => sub { my @array = (1..10)x10000; my $item = shift @array; }, index => sub { my @array = (1..10)x10000; my $item = $array[0]; }, }); cmpthese(-2, { inside => sub { my $x = 0; while ($x < 5) { my $val = $x + 2; #repeatedly declaring a new variable? say $val; $x++; } }, outside => sub { my ($x, $val); $x = 0; while ($x < 5) { $val = $x + 2; #same old variable every time say $val; $x++; } }, });
For 1) it shows shift is slightly faster (it actually just moves pointer to start of the array, no moving occur).
Rate index shift index 62.6/s -- -1% shift 63.1/s 1% --
For 2) after filtering all printed output it seems declaring my inside loop makes it slightly slower. I would say inside declaration is cleaner and speedup is not worth avoiding it.
Rate inside outside inside 132994/s -- -9% outside 146050/s 10% --
All measured on Activestate perl 5.10 on Win32 ... YMMV

-- regards, Roman


In reply to Re: shift v. indexing into an array by bobr
in thread shift v. indexing into an array by 7stud

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.