以.Distinct更快的替代品()

问题描述:

我在做一个视频游戏,性能是至关重要的。

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

我使用的是.Distinct()扩展方法来获取从列表中独特的价值。 有没有更快的方法,这样做? (即使这意味着有更多的线路code)

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)

.Distinct O(N)通话。
你不能得到任何比这更快。

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

但是,你应该确保你的 GetHash code (以及在较小程度上,等于)是尽可能快

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

根据您的情况,您可以更换名单,其中,T> 的HashSet< T> ,这将$被插入第一所p $ pvent重复。 (但具有 O(1)插入)

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)

不过,过早下结论什么需要更快之前,一定要分析您的code