We experienced some slowness in our code opening a form and it was possibly due to a for
loop with a break
that was taking a long time to execute. I switched this to an IEnumerable.Any()
and saw the form open very quickly. I am now trying to figure out if making this change alone increased performance or if it was accessing the ProductIDs
property more efficiently. Should this implementation be faster, and if so, why?
Original Implementation:
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;
}
New Implementation:
public bool ContainsProduct(int productID) {
return this.ProductIDs.Any(t => productID == t);
}
Call this an educated guess:
this.ProductIDs.Length
This probably is where the slowness lies. If the list of ProductIDs
gets retrieved from database (for example) on every iteration in order to get the Length
it would indeed be very slow. You can confirm this by profiling your application.
If this is not the case (say ProductIDs
is in memory and Length
is cached), then both should have an almost identical running time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With