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.)
|