2
    unordered_map<int, int> um;
    for (int i = 0; i < 100; i++) {
        um[i] = 1;
        cout << um.bucket_count() << endl;
    }

enter image description here Above are my test code and test result.

I found that bucket count grows like 8, 64, 512 in x86(also x64) debug mode on visual studio 2019 community environment.

Why bucket_count() is 2^n? I think it should be a prime number not a even number.

I hope your wise answers.

Thank you for reading.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
DoyoHntr
  • 87
  • 5
  • 1
    Justification for prime numbers (not visual c++): https://stackoverflow.com/questions/42523653/bucket-count-in-unordered-map – General Grievance Sep 21 '21 at 15:34
  • From math point of view yes number of buckets should be some prime number. But division operation by arbitrary value is extremely slow (this is hardware issue:lots of CPU cycles, blocks other threads doing division). So prime numbers are dropped and modulo is used which can be calculated very fast (for example by doing registry shifts). – Marek R Sep 21 '21 at 15:46
  • @S.M. I saw that prime number of bucket size is good for preventing collision in hash. So I think bucket size should be a prime number. – DoyoHntr Sep 21 '21 at 15:54
  • Can't find source where I seen this explanation (I think it was some Matt Godbolt talk on cppcon). – Marek R Sep 21 '21 at 15:55
  • @MarekR Thank you answering. So, you mean that prime numbers are not used for modulo operation and instead even numbers like 64 are used for modulo operation in hash due to fast caculating speed? – DoyoHntr Sep 21 '21 at 15:58
  • 3
    Yes the only reason is hardware performance. Risk of collision caused by not using primes is much smaller then pain of doing actual integer divisions. I will change this to an answer if/when I find good source with full explanation. – Marek R Sep 21 '21 at 16:01
  • @MarekR Re: `modulo is used which can be calculated very fast (for example by doing registry shifts)` - you probably meant `mask`, not `shift` for modulo – Vlad Feinstein Sep 22 '21 at 00:57

0 Answers0