score:2
My guess, which is a shot in dark, as any answer you might get: optimizing in the predicate case would cause more side effects. Optimization generally causes a side-effect because the GetEnumerator() of IEnumarble is not called. But in the predicate case, you can observe from the outside that it's not called in order. One might write a predicate that expects the iteration to happen in order, and going backwards would break that.
score:0
Except when an implementation of IList<T>
contains a very small number of items, optimizing the non-predicate Last
to return theList[theList.Count()-1]
is unlikely to be slower than simply enumerating from the start; it's unlikely that for any reasonable IList<T>
implementation it will be much slower. Even though the time required for some implementations of IList<T>
to find an item by index may be significantly longer than the average per-item time required to fetch data sequentially (perhaps by an order of magnitude, though probably not two), reading one item by index will generally take much less time than reading every item sequentially (random access generally won't be much slower than sequential access unless a collection is big; if in a 1,000,000-item collection the cost to read an item by index is 1,000 times the per-item time required for sequential access [an atypically-large penalty], that would still be 1,000 times as fast as reading every item).
When using Last
with a predicate, there's no guarantee how many items will need to be examined. If random access takes longer than sequential access (common), and the last match happens to occur early in the list (highly plausible), then processing the list from the start will be faster than processing from the end. Given that it would not be unreasonable for an IList<T>
implementation to take ten times as long to perform a random access as a sequential fetch, the "optimization" of reading from the back could end up making things an order of magnitude slower than "unoptimized" code that read sequentially.
If IList<T>
provided more options for reading out data, and/or included properties which roughly described the relative costs of different operations, then a Last
method could be optimized to examine list items in some other sequence, but absent such features it's better for the method to use a straightforward approach whose behavior is predictable if uninspiring, than one which tries to be clever but might sometimes perform much worse.
Source: stackoverflow.com
Related Query
- Unoptimized IEnumerable<>.Last with predicate
- IEnumerable to string delimited with commas?
- What does this C# code with an "arrow" mean and how is it called?
- Drop the last item with LINQ
- IEnumerable<T>.Contains with predicate
- IEnumerable cannot be used with type arguments
- Is there an IEnumerable implementation that only iterates over it's source (e.g. LINQ) once?
- Comma separated list with "and" in place of the last comma
- How to load just the last record from entity with LINQ?
- get last element with linq to sql
- Select from IEnumerable with Distinct/GroupBy and sorting — possible?
- Using Lambda Expressions trees with IEnumerable
- Exclude types form IEnumerable with linq
- Dynamically cast IEnumerable to IQueryable or dynamically call AsQueryable with LINQ Expressions
- Why doesn't this code compile in VS2010 with .NET 4.0?
- How do I convert IEnumerable to Collection with linq
- Splice IEnumerable with Linq
- Method with Predicate as Parameter
- When will connection be closed in case of IEnumerable with using
- How to Zip one IEnumerable with itself
- Why is this code with PredicateBuilder not working?
- How to skip last 2 records and get all other records with linq?
- Create predicate with nested classes with Expression
- Can you advise me a resource with LINQ/lambda code exercises?
- Get request to api with predicate expression as a parameter
- LINQ Source Code Available
- Split IEnumerable in three parts: "above", "item", "below" with efficiency
- LINQ: is there a way to supply a predicate with more than one parameter to where clause
- How to properly integration test Web Api controller with IEnumerable results?
- Dynamic Linq Predicate throws "Unsupported Filter" error with C# MongoDB Driver
More Query from same tag
- C# Linq full outer join on repetitive values
- How To: Use LINQ to search data for a string containing many possible types of "Single Quote"
- How to access an already defined property of an anonymous linq object?
- Specified cast not valid calling stored procedure
- How to get the last value from a model list without looping it in MVC?
- How to get the position() of an XElement?
- Dictionary<> value count c#
- When to reuse data contexts
- Flatten properties into List in EF Core
- LINQ distinct selection based on a property value
- c# wpf linq items quantity in carts shown in datagrid
- How to select objects from a list that has a property that matches an item in another list?
- GroupBy and Select extension method assistance
- Why am I getting InvalidCastException?
- Help with LINQ join
- generating list of lists with linq
- For-Loop and LINQ's deferred execution don't play well together
- How to use linq `Except` with multiple properties with different class?
- Get entire XML except root element
- Parse XML string to List/DataTable in C#
- How can I call function inside Linq to Entities query?
- C# Lambda Statement with Express Test
- Need to cast explicitly thru anonymous type in Union()
- How do i filter list of A objects based on each object's first item
- LINQ gives different results against XML and Db
- SQL Query continues running for a very long time if search term not found
- Why is For Each loop slower than linq's outer join in this example?
- How can I use "Where" with an async predicate?
- Right Join in Linq, not returning correct values
- How do I get previous element of a List<T>