Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: Using foreach to process a hash

by jdporter (Paladin)
on Oct 22, 2006 at 14:06 UTC ( [id://579859]=note: print w/replies, xml ) Need Help??


in reply to Re: Using foreach to process a hash
in thread Using foreach to process a hash

Unfortunately, DigitalKitty's benchmark suffers from a couple of major flaws. Primarily, the subs under test are doing prints. That means that timing is going to be swamped by I/O. The second thing is that the hash is so small, that in the ops performed by each sub, the ones we're trying to test (each and keys) occur very few times, relative to the overhead of calling the sub, etc.

So I offer the following benchmark, which eliminates both of those sources of error.

use Benchmark; my @words = do { local @ARGV = ( 'mondo_word_list.txt' ); <> }; my %w; @w{@words} = @words; @words = keys %w; print scalar(keys %w), " words\n"; timethese( 10, { foreach_loop => \&foreach_loop, foreach_loop_novar => \&foreach_loop_novar, while_each_loop => \&while_each_loop, array => \&array, }); sub foreach_loop { for my $key ( keys %w ) { $a = $key; $b = $w{$key}; } } sub foreach_loop_novar { for ( keys %w ) { $a = $_; $b = $w{$_}; } } sub while_each_loop { while( my( $key, $val ) = each %w ) { $a = $key; $b = $val; } } sub array { for ( @words ) { $a = $_; $b = $_; } }

Output: (slightly edited)

311142 words foreach_loop: 7 wallclock secs ( 6.22 usr foreach_loop_novar: 6 wallclock secs ( 6.17 usr while_each_loop: 5 wallclock secs ( 5.13 usr array: 1 wallclock secs ( 1.08 usr

As you can see, for large hashes, while each wins over for keys. And you also gain a little by using the default iterator on the for loop.

We're building the house of the future together.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://579859]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-19 03:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found