Reputation: 21641
I've used Linq against some collection objects (Dictionary, List). So if I want to select items based on a criteria I write a Linq query and then enumerate the linq object. So my question is that is Linq eliminating looping the main collection and as a result improving the performance?
Upvotes: 5
Views: 611
Reputation: 5358
No, in fact if you are using LINQ to SQL, the performance will be a little worse because LINQ after all is an additional layer on top of the ado.net stack.
if you using linq over objects. there are optimizations done by linq, the most important one is "Yield" which starts to yield results from an IEnumerable as it gets generated. which is better than the standard approach which has to wait for a List to be filled and returned by the function in order to iterate over it.
Upvotes: 1
Reputation: 300559
Probbaly not. LINQ lends itself to terse (hopefully) readable code.
Under the covers it's looping, unless the backing data structure supports a more efficient searching algorithm than scanning.
Upvotes: 2
Reputation: 4314
When you use the query directly, then you still loop over the whole collection. You just don't see everything, because the query will only return elements that match your filter. The overall performance will probably even take a hit, simply because of all those nested iterators that are involved. When you called ToList() on your query result, and then used this result several times, then you'd be better off performance-wise.
Upvotes: 1
Reputation: 1500695
Absolutely not. LINQ to Objects loops internally - how else could it work?
On the other hand, LINQ is more efficient than some approaches you could take, by streaming the data only when it's required etc.
On the third hand, it involves extra layers of indirection (all the iterators etc) which will have some marginal effect on performance.
Upvotes: 8