Loop implementation of List.Contains() appears faster than the built-in one. Is it? If so, why?

后端 未结 2 1951
星月不相逢
星月不相逢 2021-01-11 12:01

(This question arises from a discussion that started here)

I was comparing the timings for looking for a true value in a List u

2条回答
  •  伪装坚强ぢ
    2021-01-11 12:49

    Your loop implementation produces the same output as Contains, but you can't use it in the generic case. I.e. You would have to end up using an Equals comparison for more complex objects. The Contains implementation is performing more work than your implementation, so I don't see why you should expect it to be faster in this case.

    If you had a list of custom Person objects say, and overrode the Equals method to compare, say, their Address Name SSNumber and DateOfBirth, the loops would perform at nearly identical performance costs.

    I would expect for primitive values, then yes a loop iteration is going to outperform the generic Contains, but this is a premature optimization, you're not going to do (substantially) better than Contains for more complex object comparisons.

提交回复
热议问题