Best HashMap initial capacity while indexing a List

前端 未结 6 572
小蘑菇
小蘑菇 2021-01-31 16:46

I have a list (List list) and I want to index its objects by their ids using a map (HashMap map). I always use list.si

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 17:25

    Guava's Maps.newHashMapWithExpectedSize uses this helper method to calculate initial capacity for the default load factor of 0.75, based on some expected number of values:

    /**
     * Returns a capacity that is sufficient to keep the map from being resized as
     * long as it grows no larger than expectedSize and the load factor is >= its
     * default (0.75).
     */
    static int capacity(int expectedSize) {
        if (expectedSize < 3) {
            checkArgument(expectedSize >= 0);
            return expectedSize + 1;
        }
        if (expectedSize < Ints.MAX_POWER_OF_TWO) {
            return expectedSize + expectedSize / 3;
        }
        return Integer.MAX_VALUE; // any large value
    }
    

    reference: source

    From the newHashMapWithExpectedSize documentation:

    Creates a HashMap instance, with a high enough "initial capacity" that it should hold expectedSize elements without growth. This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't inadvertently oversizing the returned map.

提交回复
热议问题