【发布时间】:2011-09-15 14:09:37
【问题描述】:
我们的代码在打开表单时遇到了一些缓慢,这可能是由于带有break 的for 循环需要很长时间才能执行。我将其切换为IEnumerable.Any(),并很快看到表单打开。我现在正试图弄清楚单独进行此更改是否会提高性能,或者是否更有效地访问 ProductIDs 属性。这个实现是否应该更快,如果是,为什么?
原始实现:
public bool ContainsProduct(int productID) {
bool containsProduct = false;
for (int i = 0; i < this.ProductIDs.Length; i++) {
if (productID == this.ProductIDs[i]) {
containsProduct = true;
break;
}
}
return containsProduct;
}
新实施:
public bool ContainsProduct(int productID) {
return this.ProductIDs.Any(t => productID == t);
}
【问题讨论】:
-
您是否分析过您的代码并确保缓慢来自 for 循环?
-
除非您重复数百万次,否则“更快”毫无意义
-
什么是 ProductID?不可变数组?
-
你有多少产品?百万?
-
Products 属性的访问速度极慢,因为它正在执行繁重的处理(预先存在的代码)。那么该属性在 for 循环中调用的次数是否比在 .Any 枚举中调用的次数多?
标签: c# performance loops ienumerable