Hello,
I've been trying to figure out when Perl decides to double the total number of buckets for hash. According to the article "How Hashes Really Work" by Abhijit Menon-Sen, this happens when "the number of keys exceeds the number of buckets". I wrote a simple script to test that assumption.
$old_total_bucket = 8; $size = 0; for ($i = 0; $i < 65537 ; $i++ ) { $size++; $words{"$i"} = 1; $c = %words; ($fill_bucket,$total_bucket) = split(/\//,$c); if($total_bucket != $old_total_bucket) { $old_total_bucket = $total_bucket; print "For the $size keys, hash parameters are: $c \n"; } }
I print out the number of keys for all cases when the total number of buckets doubles. I use version 5.10.0. Initial part of the output is:

For the 9 keys, hash parameters are: 8/16
For the 16 keys, hash parameters are: 15/32
For the 33 keys, hash parameters are: 29/64
For the 64 keys, hash parameters are: 53/128

It seems sometimes Perl doubles the number of buckets when the number of keys is greater than the number of buckets. Sometimes the doubling occurs when the number of keys is equal to the number of buckets (say, for 16 and 64 keys). And there are cases when the doubling occurs when the number of keys is greater than the number of buckets plus one (for 32770 = 2^15 + 2 keys). I tried looking into hv.c file (for v5.12.2) and found the following lines:
} else if (xhv->xhv_keys > (IV)xhv->xhv_max) { hsplit(hv);
So this seems to indicate that doubling occurs when "the number of keys exceeds the number of buckets". However, the output of my script shows that could be some other criterion involved. So when does Perl double the number of buckets in hash? Thanks a lot for any suggestions!

In reply to When does Perl double the number of buckets in hash? by Anonymous Monk

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.