(This question arises from a discussion that started here)
I was comparing the timings for looking for a true
value in a List
u
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.