HashSet vs. List performance

前端 未结 12 2400
小鲜肉
小鲜肉 2020-11-22 09:19

It\'s clear that a search performance of the generic HashSet class is higher than of the generic List class. Just compare the has

12条回答
  •  野性不改
    2020-11-22 09:41

    It's essentially pointless to compare two structures for performance that behave differently. Use the structure that conveys the intent. Even if you say your List wouldn't have duplicates and iteration order doesn't matter making it comparable to a HashSet, its still a poor choice to use List because its relatively less fault tolerant.

    That said, I will inspect some other aspects of performance,

    +------------+--------+-------------+-----------+----------+----------+-----------+
    | Collection | Random | Containment | Insertion | Addition |  Removal | Memory    |
    |            | access |             |           |          |          |           |
    +------------+--------+-------------+-----------+----------+----------+-----------+
    | List    | O(1)   | O(n)        | O(n)      | O(1)*    | O(n)     | Lesser    |
    | HashSet | O(n)   | O(1)        | n/a       | O(1)     | O(1)     | Greater** |
    +------------+--------+-------------+-----------+----------+----------+-----------+
    
    • Even though addition is O(1) in both cases, it will be relatively slower in HashSet since it involves cost of precomputing hash code before storing it.

    • The superior scalability of HashSet has a memory cost. Every entry is stored as a new object along with its hash code. This article might give you an idea.

提交回复
热议问题