Question

Faster alternatives to .Distinct()

I'm making a video game where performance is critical.

I'm using the .Distinct() extension method to get unique value from a List. Is there a faster way to do so? (even if it means having many more lines of code)

 21  13599  21
1 Jan 1970

Solution

 41

.Distinct is an O(n) call.
You can't get any faster than that.

However, you should make sure that your GetHashCode (and, to a lesser extent, Equals) is as fast as possible.

Depending on your scenario, you may be able to replace the List<T> with a HashSet<T>, which will prevent duplicates from being inserted in the first place. (yet has O(1) insertion)

However, Always profile your code before jumping to conclusions about what needs to be faster.

2011-05-11

Solution

 7

Does it have to be a List?

Would it be possible to switch from List, to HashSet? HashSet prevents objects from being inserted into the list more than once in the first place, so the Distinct is already done.

2011-05-11