gpt4 book ai didi

c# - 多次使用 .Count 的最佳实践

转载 作者:行者123 更新时间:2023-12-01 16:20:10 24 4
gpt4 key购买 nike

那么,就性能/最佳实践等而言,以下 2 个代码块中的哪一个是“最佳”的。

每次使用时多次调用 .Count 属性。

List<string> myStrings = new List<string>();
myStrings.Add("foo");
myStrings.Add("bar");

if (myStrings.Count >= 1)
{
Console.WriteLine(myStrings.Count);
}

存储计数一次并重复使用它,因为我们可以假设列表不会发生变化。

List<string> myStrings = new List<string>();
myStrings.Add("foo");
myStrings.Add("bar");

int myCount = myStrings.Count;
if (myCount >= 1)
{
Console.WriteLine(myCount);
}

最佳答案

对于List<T>这并不是特别重要,因为 List 存储了它的计数并且能够便宜地返回它。

对于Count任意的扩展方法IEnumerable ,最好使用临时变量以避免调用Count多次。这是因为Count扩展方法必须遍历整个集合(它将检测 IList 并使用快速计数,但例如 yield return 枚举不实现 IList )。

关于c# - 多次使用 .Count 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27769755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com