Differences between Dictionary.Clear and new Dictionary()

后端 未结 8 839
情书的邮戳
情书的邮戳 2020-12-15 03:33

What are the key differences between Dictionary.Clear and new Dictionary() in C#? Which one is recommended for which cases?

8条回答
  •  遥遥无期
    2020-12-15 04:20

    As has been extensively covered, the effects are essentially the same. Clear() and new would both give you a fresh Dictionary, essentially abandoning the references to the objects inside of it, freeing them to be collected if they became unrooted.

    Technically, .Clear() would have an advantage over new if you were about to repopulate the dictionary to the same size as it was before. This is because it would have been already resized internally to hold the number of objects that you had in it before. Creating a new Dictionary would have a new internal hashtable with the default size, and it would have to be re-expanded as you added items to it.

    I would also suggest that they communicate a completely different intent, and you should use .Clear() in your code when you're dealing with the same context as before. Creating a new Dictionary implies that you are about to embark on some new logic dealing with something different than the old Dictionary, while using Clear() indicates that yes, you really wanted to just reset everything you've done so far with it.

提交回复
热议问题