java - Is it better to specify HashMap's initial capacity when it is not a power of 2 than to not specify at all? -
suppose know exact number of key-value pairs go in hashmap
, know not powerfulness of 2. in these cases, should specify initial capacity or not ? nearest powerfulness of 2 , specify still i'd know improve thing in such cases (when don't want calculate nearest powerfulness of 2).
thanks!
you should consider initial capacity hint hashmap
of approximately info expect. providing right initial capacity, minimize number of times map has rebuilt in order scale up. if, instance, knew planning insert 1000000 records, constructing map 1,000,000 initial capacity, ensure, @ construction time, allocate plenty memory handle many inserts. after point, future inserts map may require big o(n) operation during map.put()
phone call in order resize.
thinking of initial capacity hint, rather instruction expect hashmap
follow, may help see optimization you're describing unnecessary. hashmap
designed behave in normal circumstances, , while providing initial capacity can help marginally, it's not going have huge impacts on code unless building many new big maps time. in such case specifying capacity avoid intermediate table resizing, that's all.
as documented, introduce unnecessary slowdowns if specified too big of initial capacity:
iteration on collection views requires time proportional "capacity" of hashmap
instance
however in practice wasted memory of allocating such big maps cause problems sooner slower iteration speed.
be sure read why hashmap require initial capacity powerfulness of two? well.
one thing might consider switching guava's immutablemap implementation; if know in advance contents of map, , don't expect alter them, immutable collections prove easier work , use less memory mutable counterparts.
here's quick inspections did using scala's repl (and personal utility functions) inspect what's going on within hashmap
(java 1.7):
// initialize capacity=7 scala> new hashmap[string,string](7) res0: java.util.hashmap[string,string] = {} scala> getprivate(res0, "table").length res1: int = 8 scala> ... set 7 values // still internally using same array scala> getprivate(res0, "table").length res9: int = 8 // specifying capacity 9 allocates 16-lenth array scala> getprivate(new hashmap[string,string](9), "table").length res10: int = 16 // copying our first map new map interestingly // allocates default 16 slots, rather 8 scala> getprivate(new hashmap[string,string](res0), "table").length res11: int = 16 scala> ... set 10 more values in our map scala> getprivate(res0,"table").length res22: int = 32 // copying 1 time again jumps 32 capacity scala> getprivate(new hashmap[string,string](res0),"table").length res23: int = 32
java hashmap java-6
No comments:
Post a Comment