Why is Arrays.fill() not used in HashMap.clear() anymore?

后端 未结 5 497
太阳男子
太阳男子 2021-01-30 16:02

I noticed something strange in the implementation of HashMap.clear(). This is how it looked in OpenJDK 7u40:

public void clear() {
    modCount++;
          


        
5条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 16:24

    There is no actual difference in the functionality between the 2 version's loop. Arrays.fill does the exact same thing.

    So the choice to use it or not may not necessarily be considered a mistake. It is left up to the developer to decide when it comes to this kind of micromanagement.

    There are 2 separate concerns for each approach:

    • using the Arrays.fill makes the code less verbose and more readable.
    • looping directly in the HashMap code (like version 8) peformance wise is actually a better option. While the overhead that inserting the Arrays class is negligible it may become less so when it comes to something as widespread as HashMap where every bit of performance enhancement has a large effect(imagine the tiniest footprint reduce of a HashMap in fullblown webapp). Take into consideration the fact that the Arrays class was used only for this one loop. The change is small enough that it doesn't make the clear method less readable.

    The precise reason can't be found out without asking the developer who actually did this, however i suspect it's either a mistake or a small enhancement. better option.

    My opinion is it can be considered an enhancement, even if only by accident.

提交回复
热议问题