The reason for the speed difference is because if (%hash) {} ends being implemented internally as

sv = sv_newmortal(); if (HvFILL((HV*)hv)) Perl_sv_setpvf(aTHX_ sv, "%ld/%ld", (long)HvFILL(hv), (long)HvMAX(hv) + 1); else sv_setiv(sv, 0);

So what happens is a new SV is created, its then populated with a string using something like sprintf.

This can be compared against the keys %hash option where an extra opcode is executed, BUT that opcode involves creating an SvIV only and therefore requires no memory allocation, no conversion of longs to strings, etc.

So the bottom line is that if you are concerned about speed use the keys form. In Perl 5.10 we will try to make this an internal optimisation, (internally using if (keys %foo) when the user typed if (%foo) )but its not exactly priority, at least not for me :-).

Update: Well, I gave it a try just to see what was involved, and before I knew it I was sending off patches. So theres a half decent chance this will be fixed in perl 5.10

---
$world=~s/war/peace/g


In reply to Re^3: Benchmark of hash emptiness test by demerphq
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.