Search code examples
performancememory-managementconstructorunordered-mapallocator

Is it always good to set the bucket count in the constructor if we know the number of elements before hand as against reserving them later?


I see that creating an empty unordered_map sets the bucket count to default ( in my case it's 11). After which if i call unordered_map.reserve(n) where the n is quite big it rehashes immediately. So is it a good idea to pass a big number (possibly n as in reserve to the constructor of unordered_map so as to save a rehash. Correct me if i am wrong in my understanding.


Solution

  • Sure... if you know how many elements you'll have, it's good to let the constructor know too. The constructor wouldn't have an argument for it if it wasn't potentially useful. It's just a hint though, your suggested minimum, but I'd imagine all standard libraries would honour it, possibly after rounding it up to some power-of-two or prime depending on other implementation/design decisions they've made. Balancing the improved speed of creation/population, the risk/cost is a maintenance one: if you let your "hint" get out of sync with your actual needs, you may end up wasting memory or losing performance (e.g. having too low a load factor may mean fewer cache page hits).