Is Java HashMap.clear() and remove() memory effective?

后端 未结 4 407
梦毁少年i
梦毁少年i 2020-12-02 12:40

Consider the follwing HashMap.clear() code:

 /**
 * Removes all of the mappings from this map.
 * The map will be empty after this call returns.         


        
4条回答
  •  旧巷少年郎
    2020-12-02 13:01

    The idea is that clear() is only called when you want to re-use the HashMap. Reusing an object should only be done for the same reason it was used before, so chances are that you'll have roughly the same number of entries. To avoid useless shrinking and resizing of the Map the capacity is held the same when clear() is called.

    If all you want to do is discard the data in the Map, then you need not (and in fact should not) call clear() on it, but simply clear all references to the Map itself, in which case it will be garbage collected eventually.

提交回复
热议问题