LINQ Performance Improvements in .NET Framework Service Pack 1

There are three performance improvements in Service Pack 1. These improvements target LINQ to Objects and LINQ to SQL.

LINQ to Objects:

 

A new implementation of performing queries on Where and Select on List<T>, folds pipelines of multiple enumerable objects into single specialized enumerables. This
produces substantial improvement in base overhead of common LINQ to
Objects queries (at times 30+%).

Cast<T> breaking change: This is a bug fix and a breaking change (see Breaking Change in Linq Queries Using Explicitly-Typed Range Variables for background). The intended use of the NET FX 3.5 Cast<T>
extension method is querying over non-generic collection types, whose
elements require either a reference conversion or an unboxing step to
be used in a generic query context. A late change VS 2008 cycle allowed
the cast to succeed in more situations than intended, such as
converting float values to int, where it should instead be throwing an
InvalidCastException. The breaking change reverts the beta2 behavior
and improves performance by simplifying the implementation of
CastIterator<T>. Value conversions and explicitly-defined user
conversions cause an InvalidCastException instead of being allowed (as in RTM).

 

var stringList = new ArrayList { "foo", "bar" };
var intList = new ArrayList { 3, 4, 5 };

 

var strings = from string s in stringList   
              select s;

var ints = from int i in intList           
           select i;

The above queries compile to  

var strings = stringList.Cast<string>();
var ints = intList.Cast<int>();

You can imagine a simplified implementation 

static IEnumerable<T> CastIterator<T>(IEnumerable source)
{
   foreach (object obj in source) yield return (T)obj;
}

 

 

LINQ to SQL:

 

This
too is a bug fix. The original idea was to optimize queries based on a id, that are expected to return singletons. If an object with a matching key is already in the DataContext, then executing against the SQL database is a waste of time. Before the bug fix (pre-SP1), this query would have been translated to SQL and executed on the databsae. Now that bug has been fixed.
So an id-based query will not cause a trip to the database. This
results in a dramatic performance improvement (one hash table lookup instead
of SQL translation + SQL query execution) in an admittedly narrow but
common scenario.


share save 171 16 LINQ Performance Improvements in .NET Framework Service Pack 1

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply