The perlfunc manpage says about the keys function:
As an lvalue keys allows you to increase the number of hash buckets allocated for the given hash. This can gain you a measure of efficiency if you know the hash is going to get big.

I decided to try benchmarking it to see how much it did increase efficiency and ran this code:
use Benchmark; timethese( 100, {with => q{ my %hash; keys( %hash ) = keys( %hash ) = 10000; foreach $i (1 .. 10000) { $hash{"key$i"} = $i; } }, without => q{ my %hash; foreach $i (1 .. 10000) { $hash{"key$i"} = $i; } }, });

My results from this show that using keys didn't acually increase efficiency at all...
Benchmark: timing 100 iterations of with, without... with: 14 wallclock secs (13.73 usr + 0.04 sys = 13.77 CPU) @ 7 +.26/s (n=100) without: 14 wallclock secs (13.86 usr + 0.00 sys = 13.86 CPU) @ 7 +.22/s (n=100)

I would think that since this would make it so the hash wouldn't constantly have to be expanded this would greatly increase efficiency. Printing out the number of buckets filled and total number of buckets shows that without allocating the keys beforehand, the hash is reallocated somehow when expanded whereas it isn't when you do allocate:
1/16384 2/16384 3/16384 4/16384 5/16384 6/16384 7/16384 8/16384 9/16384 10/16384
vs.
4/8 5/8 6/8 7/8 7/8 7/8 7/8 7/8 12/16 13/16 13/16 13/16 etc...
Am I doing something wrong in my benchmark? Or is there some magic going on behind the scenes of hashes that make expanding the hash not an issue? Thanks

In reply to Using keys to increase hash efficiency by Boogman

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.