I can't answer your question, however it is interesting to consider the two cases:

use strict; use warnings; use Benchmark qw(cmpthese); my $HASHSIZE = 1e3; my %hash; test (); @hash{1..$HASHSIZE} = () x $HASHSIZE; test (); sub test { my $_keys = keys %hash; my $_scalar_keys = scalar(keys %hash); my $_scalar = scalar(%hash); my $_if = %hash; print "_keys: $_keys\n"; print "_scalar_keys: $_scalar_keys\n"; print "_scalar: $_scalar\n"; print "_if: $_if\n"; cmpthese(-1, { _keys => sub {if (keys %hash) { ; }}, _scalar_keys => sub {if (scalar(keys %hash)) { ; }}, _scalar => sub {if (scalar(%hash)) { ; }}, _if => sub {if (%hash) { ; }}, } ); }

Prints:

_keys: 0 _scalar_keys: 0 _scalar: 0 _if: 0 Rate _scalar _if _keys _scalar_ +keys _scalar 5217686/s -- -10% -15% +-18% _if 5766838/s 11% -- -6% +-10% _keys 6136894/s 18% 6% -- + -4% _scalar_keys 6387143/s 22% 11% 4% + -- _keys: 1000 _scalar_keys: 1000 _scalar: 629/1024 _if: 629/1024 Rate _scalar _if _keys _scalar_ +keys _scalar 379905/s -- -1% -92% +-92% _if 384350/s 1% -- -92% +-92% _keys 4930608/s 1198% 1183% -- + -1% _scalar_keys 4996935/s 1215% 1200% 1% + --

Note that I prefer to use cmpthese and that unless really huge numbers of tests are made without anything much else going on, the time is sufficiently small as to not matter anyway.


DWIM is Perl's answer to Gödel

In reply to Re: Benchmark of hash emptiness test by GrandFather
in thread Benchmark of hash emptiness test by andreas1234567

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.