If i did understand exactly, from your example, that the power of 2 should be a prime.

I don't know, wolfram says "prime factorization"...

I looked at perldata and keys and saw indeed that the number of buckets is a power of 2 but it was not explained why.

Oh, why? because :) its coded that way :D

newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */ .. Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);

Programmers just love to do things in powers of two

perl hash presize why power of 2 How Hashes Really Work - Perl.com

In principle, a hashing function returns an array index directly; in practice, it is common to use its (arbitrary) return value modulo the number of buckets as the actual index. (Using a prime number of buckets that is not too close to a power of two tends to produce a sufficiently uniform key distribution.)
A Hash Function for Hash Table Lookup
The best hash table sizes are powers of 2. There is no need to do mod a prime (mod is sooo slow!).
Hash table
In the case that the array size is a power of two, the remainder operation is reduced to masking, which improves speed, but can increase problems with a poor hash function.

So there you have it, power of two, its for the speed


In reply to Re^3: how are the number of buckets in a perl hash chosen by Anonymous Monk
in thread how are the number of buckets in a perl hash chosen by david2008

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.