[SOLVED] C# Linq ANY vs ALL – Performance

Issue

I am trying to figure out how does ANY and ALL work in Linq.

Lets say I have 100k records in a list. Which one should perform faster?

if(recordsList.All(r => r.Deleted)) { }

or

if(!recordsList.Any(r => !r.Deleted)) { }

I would think that ANY should perform faster in case the first record on the list is deleted it should stop and return true, instead of using ALL which will always check whole list… right?

Solution

See how Any works internally:

public static bool Any<TSource>(this IEnumerable<TSource> source, 
                                Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (predicate == null)
    {
        throw Error.ArgumentNull("predicate");
    }
    foreach (TSource local in source)
    {
        if (predicate(local))
        {
            return true;
        }
    }
    return false;
}

So it stops once found a predicate that is evaluated to true.

In the same manner All stops once a predicate that is evaluated to false:

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (predicate == null)
    {
        throw Error.ArgumentNull("predicate");
    }
    foreach (TSource current in source)
    {
        if (!predicate(current))
        {
            return false;
        }
    }
    return true;
}

So I think the answer here is that both options should have similar to no difference.

Answered By – Yosi Dahari

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *