http://www.perlmonks.org?node_id=36140

rdw has asked for the wisdom of the Perl Monks concerning the following question:

Having been caught once again by 'each' not resetting, I decided to do some benchmarks to compare the performance of a while loop with 'each' and a foreach loop with 'keys'.

The results surprised me, so I'm seeking enlightenment - can anybody explain this one?

Here is the code I tried... (obviously I could have used 'values' in the second case, but this code was constructed just for benchmarking)
#! /usr/bin/perl -w use Benchmark qw(cmpthese); use strict; use integer; my %hash; for (my $i = 0; $i < 1000; $i++) { $hash{$i} = $i; } sub e { my $total = 0; keys %hash; while (my($k, $v) = each %hash) { $total += $v; last if $total > 500; } } sub k { my $total = 0; foreach my $k (keys %hash) { my $v = $hash{$k}; $total += $v; last if $total > 500; } } cmpthese(100000, { 'each' => \&e, 'keys' => \&k });

And here are the results...

Benchmark: timing 100000 iterations of each, keys...
      each:  1 wallclock secs ( 0.61 usr +  0.01 sys =  0.62 CPU) @ 161290.32/s (n=100000)
      keys: 93 wallclock secs (90.03 usr +  0.77 sys = 90.80 CPU) @ 1101.32/s (n=100000)
         Rate   keys   each
keys   1101/s     --   -99%
each 161290/s 14545%     --

...but... (and this is the weird bit) if I comment out the line which breaks out of the loop ('last if...') then the results are completely different... (I dropped the number of iterations - hope this hasn't changed too much - I got bored waiting for it)

Benchmark: timing 1000 iterations of each, keys...
      each:  2 wallclock secs ( 2.77 usr +  0.00 sys =  2.77 CPU) @ 361.01/s (n=1000)
      keys:  3 wallclock secs ( 2.36 usr +  0.00 sys =  2.36 CPU) @ 423.73/s (n=1000)
      Rate each keys
each 361/s   -- -15%
keys 424/s  17%   --

So it seems that 'each' is much quicker, but only if you plan on leaving the loop early - which is when the not resetting gotcha kicks in.

Now I understand that 'keys' would have to generate a list which might be expensive I guess, but I'm still a bit puzzled by the results. Perhaps there is something else going on.

Have fun,

rdw