Monks,
I want to know if a hash is empty. Since I'll be doing it very often,
I want is to perform as fast as possible. The
defined section of
perlfunc says:
if (%a_hash) { print "has hash members\n" }
To my surprise
Benchmark,
says that
if(keys %hash) is roughy
5 times faster
than
if(%hash).
Less surprisingly, it also seems that
if (scalar(%hash)) and
if
(%hash) performs equally fast, and that
if (scalar(keys %hash))
and
if(keys %hash) also performs equally fast.
#!/usr/bin/perl -sw
use strict;
use Benchmark;
our $HASHSIZE ||= 1e3;
our $ITERATIONS ||= 1e7;
my %hash = ();
# Init hash
for (my $i=0; $i<$HASHSIZE; $i++) {
$hash{$i} = 1;
}
timethese($ITERATIONS,
{
_keys => sub {
if (keys %hash) { ; }
},
_scalar_keys => sub {
if (scalar(keys %hash)) { ; }
},
_scalar => sub {
if (scalar(%hash)) { ; }
},
_if => sub {
if (%hash) { ; }
},
}
);
__END__
=pod
=head1 NAME
bm_hash_emptiness.pl - benchmark hash emptiness tests.
=head1 SYNOPSIS
./bm_hash_emptiness.pl -ITERATIONS=1e7 -HASHSIZE=1e4
=head1 RESULTS
$ ./bm_hash_emptiness.pl -ITERATIONS=1e7 -HASHSIZE=1e4
Benchmark: timing 1e7 iterations of _if, _keys, _scalar, _scalar_key
+s...
_if: 14 wallclock secs (14.65 usr + 0.01 sys = 14.66 CPU)
_keys: 2 wallclock secs ( 1.99 usr + 0.00 sys = 1.99 CPU)
_scalar: 16 wallclock secs (15.03 usr + 0.01 sys = 15.04 CPU)
_scalar_keys: 2 wallclock secs ( 2.40 usr + 0.00 sys = 2.40 CPU)
=head SEE ALSO
perlfunc
=cut
Should I stick to the
advice from
perlfunc and use
if (%hash) even when it seems to be slower than the alternative?
--
Andreas
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.