Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is IEnumerable.Any faster than a for loop with a break?

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);
}
like image 574
Ian R. O'Brien Avatar asked Jun 15 '11 14:06

Ian R. O'Brien


1 Answers

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.

like image 123
Oded Avatar answered Oct 14 '22 16:10

Oded