Is there a performance difference between these two algorithms for shuffling an IEnumerable?

后端 未结 3 538
借酒劲吻你
借酒劲吻你 2020-12-18 09:02

These two questions give similar algorthims for shuffling an IEnumerable:

  • C#: Is using Random and OrderBy a good shuffle algorithm?
  • Can you enumerate
3条回答
  •  旧巷少年郎
    2020-12-18 09:29

    The first algorithm is O(n) as it has a loop which performs an O(1) swap on each iteration. The second algorithm is O(n^2) as it performs an O(n) RemoveAt operation on each iteration. In addition indexers on lists are slower than indexes on arrays because the former is a method call whereas the latter is an IL instruction.

    So out of the two the first one is likely to be faster. That said, if you're after performance, why bother yielding the results? It's already converting to an array so just shuffle that in place and return the array directly (or wrapped in a ReadOnlyCollection if you're worried about people changing it) which is probably faster still.

    On a side note, both methods have bugs that the behaviour of Random when used by multiple threads is undefined, so they should probably use a thread-safe random number generator.

提交回复
热议问题