Why is Dictionary.First() so slow?

前端 未结 5 1109
自闭症患者
自闭症患者 2020-12-11 16:35

Not a real question because I already found out the answer, but still interesting thing.

I always thought that hash table is the fastest associative container if you

5条回答
  •  一个人的身影
    2020-12-11 17:30

    Dictionary maintains a hash table.

    Its enumerator will loop through the buckets in the hash table until it finds a non-empty bucket, then return the value in that bucket.
    Once the dictionary grows large, this operation becomes expensive.
    In addition, removing an item from the dictionary doesn't shrink the buckets array, so the First() call gets slower as you remove items. (Because it has to loop further to find a non-empty bucket)

    Therefore, repeatedly calling First() and removing is O(n2).


    By the way, you can avoid the value lookup like this: (This will not make it noticeably faster)

    var kvp = todo.First();
    
    //Use kvp.Key and kcp.Value
    

提交回复
热议问题