views:

28

answers:

1

I'm wondering if LINQ methods like .Last and .Skip are optimized for arrays, List and the such. E.g. for an array I could do _array[_array.Length] to get the last element. Does _array.Last() actually enumerate through all elements and then return the last or is there actually some optimization built in?

Might have to forgo fluency for performance if not.

Thanks.

+1  A: 

Last() is optimized when there isn't a predicate... it could be optimized even if there is a predicate (by working back from the end), but it isn't.

I don't think Skip is optimized - although again, it could be.

Basically most of LINQ to Objects is optimized where it can be (for ICollection<T>, ICollection, and IList<T>) but there's still room for more to come.

Jon Skeet
Thanks. Do you by chance have the link to the documentation stating the optimization? I was searching for but couldn't find it.
fung
@fung: You may use Reflector to read the code your self.
Albin Sunnanbo