What is LINQ?
LINQ (Language Integrated Query) is a great set of new features that evolved out of the LINQ Project (http://msdn.microsoft.com/en-us/netframework/aa904594.aspx).
LINQ allows you to execute “SQL Like” queries against different kinds of data sources (.NET objects/lists, SQL, XML).
Its very powerful and it helps developers to query for certain information instead of “hand-coding” loops, if’s and switches.
How fast is LINQ compared to “traditional” looping?
In order to answer this question I implemented a small sample application which creates random objects based on the object model of our GoSpace “Last Minute Offer” Web Service. Here is a short explaination about the Model:
A Travel Offer contains id (int), price (double), Planet, Flight, Accomodation, Meal and Room Type. Planet, Flight, Accomodation, Meal and Room Type are represented as objects. Flight for example further references objects like Ship and SpacePort.
In my sample scenario I created 100000 Offer objects with all its dependant objects. I then implemented the following 4 scenarios with LINQ and with the “standard” approach of simply iterating through the objects:
* Query 1: SELECT all Offers with a price higher than 1000
* Query 2: SELECT all Offers with a Kosher Meal Type
* Query 3: SELECT all Offers to Mars
* Query 4: SELECT all Offers to Mars and return the Flight Information
I configured the sample application with dynaTrace and was not at all surprised that the LINQ version of the queries took longer. It was however interesting that the overhead was between 10% and 30%.
Here is a comparision between the 4 queries with and without LINQ:
Diving deeper into LINQ
I also created a Knoweldge Sensor Pack for LINQ (downloadable in our Community Portal) which shows the internals of LINQ. Additionally to the above mentioned scenarios I executed LINQ queries that used features like aggregation, sorting, …
Here is a sample PurePath of a more advanced LINQ query:
LINQ is easy to use and very powerful. In a simple scenario one has to decide whether a simple nested loop might be the better approach – especially when it comes down to performance.
The Knowledge Sensor Pack will definitely help developers to understand the internals of LINQ and might give them hints to improve their queries.