大神们在创建集合的时候,大多数都设置了一个预估的初始容量(2的幂数),而不是直接采用默认的初始容量( HashMap 中是16),就像下面这样:
/** Map from dependency type to corresponding autowired value */
private final Map, Object> resolvableDependencies = new ConcurrentHashMap, Object>(16);
/** Map of bean definition objects, keyed by bean name */
private final Map beanDefinitionMap = new ConcurrentHashMap(256);
/** Map of singleton and non-singleton bean names, keyed by dependency type */
private final Map, String[]> allBeanNamesByType = new ConcurrentHashMap, String[]>(64);
/** Map of singleton-only bean names, keyed by dependency type */
private final Map, String[]> singletonBeanNamesByType = new ConcurrentHashMap, String[]>(64);
/** List of bean definition names, in registration order */
private volatile List beanDefinitionNames = new ArrayList(256);
/** List of names of manually registered singletons, in registration order */
private volatile Set manualSingletonNames = new LinkedHashSet(16);
大神们这样写肯定是有好处的。不太了解其它集合类的实现,就以 HashMap 为例看一下。HashMap 底层的存储结构是一个 Entry 对象的数组(Java 8中是 Node 对象的数组),默认初始容量是16,负载因子是0.75。也就是说当元素个数超过16*0.75=12时,就要进行扩容,将数组大小扩大一倍,并计算元素在新数组中的位置,这个过程是比较耗费性能的。所以,个人觉得大神们这样写是因为如果直接采用默认的初始容量,那么在元素个数较少时,会浪费空间;元素个数较多时,又会造成频繁的扩容,耗费性能。