问题描述
我有一个包含很多值的 List<bool>
.检查列表中的每一项是否等于 false
的最有效方法是什么?
I have a List<bool>
with lots of values. What is the most efficient way to check if every single item in the list equals false
?
推荐答案
这里没有提到的一个明显更快的解决方案是使用 包含
A significantly faster solution, not mentioned here, is using Contains
if (!myList.Contains(true))
// Great success - all values false!
我将 Contains
与 IEnumerable.Any
进行了比较,Contains
返回速度更快.在我的测试中,IEnumerable.All
的性能与 IEnumerable.Any
相同,可能在后台对这两个函数使用了类似的算法.我还检查了 IEnumerable.Exists
,它的性能优于 IEnumerable.Any
和 IEnumerable.All
,但仍然比 Contains
慢代码>.
I have compared Contains
against IEnumerable.Any
and Contains
returns faster. In my tests IEnumerable.All
performed the same as IEnumerable.Any
, perhaps a similar algorithm is used for both these functions under the hood. I also checked IEnumerable.Exists
which performed better than IEnumerable.Any
and IEnumerable.All
, but was still slower than Contains
.
在 10,000,000 个布尔条目列表中(我也尝试了 0 和 1 个条目,结果相似),我得出了以下指标:
Of a list of 10,000,000 bool entries (I also tried 0 and 1 entries, with similar results), I came up with the following metrics:
经过任何 = 95ms
全部经过 = 88 毫秒
Elapsed via All = 88ms
经过 Exists = 27ms
Elapsed via Exists = 27ms
经过包含 = 17ms
Contains 比 Any 快约 5.59 倍!
用以下代码测试:
// setup initial vars
var myList = new List<bool>();
for (int x = 0; x < 10000000; x++)
myList.Add(false);
var containsAllFalse = false;
Stopwatch sw = new Stopwatch();
// start test
sw.Start();
containsAllFalse = !myList.Any(x => x);
sw.Stop();
// get result for Any
var timeAny = sw.ElapsedMilliseconds;
// reset variable state (just in case it affects anything)
containsAllFalse = false;
// start test 2
sw.Restart();
containsAllFalse = myList.All(x => x == false);
sw.Stop();
// get result for All
var timeAll = sw.ElapsedMilliseconds;
// reset variable state (just in case it affects anything)
containsAllFalse = false;
// start test 3
sw.Restart();
containsAllFalse = !myList.Exists(x => x == true);
sw.Stop();
// get result for All
var timeExists = sw.ElapsedMilliseconds;
// reset variable state (just in case it affects anything)
containsAllFalse = false;
// start test 4
sw.Restart();
containsAllFalse = !myList.Contains(true);
sw.Stop();
// get result from Contains
var timeContains = sw.ElapsedMilliseconds;
// print results
var percentFaster = Math.Round((double)timeAny / timeContains, 2);
Console.WriteLine("Elapsed via Any = {0}ms", timeAny);
Console.WriteLine("Elapsed via All = {0}ms", timeAll);
Console.WriteLine("Elapsed via Exists = {0}ms", timeExists);
Console.WriteLine("Elapsed via Contains = {0}ms", timeContains);
Console.WriteLine("Contains is ~{0}x faster than Any!", percentFaster);
请注意,这仅适用于类型只能具有两种状态的类型(即它不适用于 >2 状态的变量,例如 Nullable<bool>
)em>
Note this will only work with types where type can only have two states (i.e. it won't work variables of >2 states, such as Nullable<bool>
)
这篇关于布尔列表检查列表中的每个项目是否为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!