在使用 Contains() 之前从 IEnumerable 实例化 HashSet 是一个好习惯吗?

问题描述 投票:0回答:0

下面的代码片段用另一个过滤

IEnumerable
,用作黑名单。过滤后的集合会迭代远程获取的内容(延迟加载、YouTube Api)。

IEnumerable<string> contentThatCanBeHuge = this.FetchContentThatCanBeHuge();
IEnumerable<string> blackListContent = this.FetchBlackListContent();
return contentThatCanBeHuge.Where(x => !blackListContent.Contains(x.Id));

IEnumerable.Contains()
方法的时间复杂度为
O(n)
,因此
IEnumerable.Where()
调用可能需要一段时间。

另一方面,

HashSet.Contains()
O(1)
。从
HashSet
实例化
IEnumerable
似乎是
O(n)

如果黑名单即将被多次使用,并且不考虑空间复杂度,那么在使用之前将其变成

HashSet
是一个好方法还是这只是过早的优化?

c# time-complexity hashset premature-optimization
© www.soinside.com 2019 - 2024. All rights reserved.