I believe LanX's performance concern is whether a hash with 100,000 elements must extend the perl stack to 200,000 elements before beginning the loop.

Extending the stack by one element or by 200,000 has the same fixed performance cost.

It's cheaper in fact, because it avoids 99,999 checks to see if the stack needs to be extended.

Also I would not say that "it uses the built-in iterator" unless it picks up from the current position of the internal iterator

By your logic, keys and values don't use the iterator.

my %h = ( a => 5, b => 6, c => 7 ); each %h; say for keys( %h );
b c a

That's wrong. %h in list context, keys and values all use the iterator. They just reset it first. You can see this by the fact that it's not left in its previous state.

my %h = ( a => 5, b => 6, c => 7 ); each %h; while ( my $k = each( %h ) ) { say $k; } say "--"; each %h; my @a = %h; while ( my $k = each( %h ) ) { say $k; }

If the iterator wasn't used, you'd see the same output twice. But because the iterator is used, you see something like

c a -- b c a

In fact, keys and values are specifically documented to reset the iterator, and they're specifically document to do this and nothing else in void context. (I don't know if %h in list context is specifcally documented to reset the iterator.)


In reply to Re^10: Why does each() always re-evaluate its argument? ("for_list" ) by ikegami
in thread Why does each() always re-evaluate its argument? by Darkwing

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.