Hashcode bucket distribution in java

前端 未结 3 1063
终归单人心
终归单人心 2021-01-05 15:37

Suppose I need to store 1000 objects in Hashset, is it better that I have 1000 buckets containing each object( by generating unique value for hashcode for each object) or ha

3条回答
  •  情书的邮戳
    2021-01-05 16:16

    Roughly one bucket per element is better for the processor, too many buckets is bad for the memory. Java will start with a small amount of buckets and automatically increase the capacity of your HashSet once it starts filling up, so you don't really need to care unless your application has issues performance and you've identified a hashset as the cause.

    If you several elements in each bucket, lookups start taking longer. If you have lots of empty buckets, you're using more memory than you need and iterating over the elements takes longer.

    This seems like a premature optimization waiting to happen though - the default constructor is fine in most cases.

提交回复
热议问题