What is the simplest way to achieve O(n) performance when creating the union of 3 IEnumerables?

前端 未结 3 1566
心在旅途
心在旅途 2021-02-07 00:51

Say a, b, c are all List and I want to create an unsorted union of them. Although performance isn\'t super-critical, they might have 10,000 entries in each

3条回答
  •  你的背包
    2021-02-07 01:18

    Union is O(n).

    a.Union(b).Union(c) is less efficient in most implementations than a.Union(b.Concat(c)) because it creates a hash-set for the first union operation and then another for the second, as other answers have said. Both of these also end up with a chain of IEnumerator objects in use which increases cost as further sources are added.

    a.Union(b).Union(c) is more efficient in .NET Core because the second .Union() operation produces a single object with knowledge of a, b and c and it will create a single hash-set for the entire operation, as well as avoiding the chain of IEnumerator objects.

提交回复
热议问题