score:6

Accepted answer

current optimisations that i'm aware of:

  • count uses the count property if the sequence implements icollection<t> and a predicate isn't used. (in .net 4 count is also optimised for the non-generic icollection.)

  • elementat/elementatordefault access by index if the sequence implements ilist<t>.

  • last/lastordefault access by index if the sequence implements ilist<t> and a predicate isn't used.

  • toarray/tolist use the count property to allocate memory more efficiently if the sequence implements icollection<t>. (but neither of them optimise for icollection.)

optimisations that could be there but aren't:

  • last/lastordefault don't optimise in the case where a predicate is used. there's no reason why they couldn't optimise for ilist<t>, iterating backwards through the list and accessing each element by index.

  • sequenceequal could optimise for icollection<t> and icollection, using the count property to determine if the lists are the same length and breaking out early if they're not.

  • skip could optimise for ilist<t>, accessing the elements by index and starting directly at index n rather than iterating and discarding the first n elements.

  • toarray/tolist could also optimise for icollection, using the count property to allocate memory more efficiently.

  • todictionary could optimise for icollection<t> and icollection, using the count property to allocate memory more efficently.

score:13

try the .net reflector. it's a great tool for browsing class libraries, it has a powerful decompiler which let's you view the source code pretty much as it was written.

e.g. the count() extension method is implemented like this

if (source == null)
{
    throw error.argumentnull("source");
}
icollection<tsource> is2 = source as icollection<tsource>;
if (is2 != null)
{
    return is2.count;
}
icollection is3 = source as icollection;
if (is3 != null)
{
    return is3.count;
}
int num = 0;
using (ienumerator<tsource> enumerator = source.getenumerator())
{
    while (enumerator.movenext())
    {
        num++;
    }
}
return num;

at the off chance that the source does not implement the collection interface you'll have to count to get the actual acount. browsing the code this way is a great way to learn.


Related Query

More Query from same tag