in reply to Re:x2 Counting keys with defined or undefined elements in a hash
in thread Counting keys with defined or undefined elements in a hash
My aesthetic sense is somewhat offended by scanning the list twice using grep.
Mine too - as well as my common sense (no offense broquaint ;-)
Here's a quick benchmark of my first thought (&for_values), my second thought (&grep_subtract) your method and broquaint's double grep.
#!/usr/bin/perl use strict; use warnings; use Benchmark 'cmpthese'; my %hash = ( foo => 1, bar => 1, baz => 1, one => undef, two => undef, three => undef, ); my ($defined, $undef, $count, @def); sub for_values { defined($_) ? $defined++ : $undef++ for values %hash; } sub grep_values { $defined = scalar (grep defined, values %hash); $undef = scalar (grep !defined, values %hash); } sub grep_subtract { $defined = scalar (grep defined, values %hash); $undef = (scalar keys %hash) - $defined; } sub for_array { $def[ defined $_ ? 1 : 0]++ for values %hash; } cmpthese ( -5, { for => \&for_values, grep => \&grep_values, grep_two => \&grep_subtract, for_array => \&for_array, } ) __END__
I'll just post the summary output from cmpthese: (perl 5.6.1) Rate for_array grep for grep_two for_array 82736/s -- -8% -12% -44% grep 90290/s 9% -- -4% -39% for 94074/s 14% 4% -- -37% grep_two 148846/s 80% 65% 58% --
Using grep is deceptively fast - it looks like using the ternary operator in a single loop is slower than looping twice!
By far the fastest of these is using keys to find the total number of hash elements and subtract the number of defined elements.
I wonder how this would perform as the hash grows?
Update: Moved Benchmark results outside of readmore...
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Re:x2 Counting keys with defined or undefined elements in a hash
by broquaint (Abbot) on Jun 05, 2003 at 18:45 UTC | |
by jsprat (Curate) on Jun 05, 2003 at 19:01 UTC |
In Section
Seekers of Perl Wisdom