in linq why are subsequent calls of IEnumerable.Intersect so much faster

后端 未结 5 1265
时光说笑
时光说笑 2021-01-19 18:10

while looking at this question C# Similarities of two arrays it was noted that the initial linq call was significantly slower than subsequent calls. What is being cached th

5条回答
  •  抹茶落季
    2021-01-19 19:07

    Enumerable.Intersect does not do any caching. It is implemented using a HashSet. The first sequence is added to the HashSet. Then the second sequence is removed from the HashSet. The remaining elements in the HashSet is yielded as an enumerable sequence of elements. You will have to actually enumerate the HashSet to pay the cost of creating the HashSet. This implementation is suprisingly efficient even for small collections.

    If you see a difference in performance in subsequent calls it is not because Enumerable.Intersect does any caching but probably because you need to "warm up" your benchmark.

提交回复
热议问题