In performance point of view what should you use “Nested foreach’s” or “lambda/linq queries”?
In performance point of view what should you use Nested foreach’s or lambda/linq queries?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Write the clearest code you can, and then benchmark and profile to discover any performance problems. If you do have performance problems, you can experiment with different code to work out whether it’s faster or not (measuring all the time with as realistic data as possible) and then make a judgement call as to whether the improvement in performance is worth the readability hit.
A direct
foreachapproach will be faster than LINQ in many cases. For example, consider:Now there are two
whereclauses and aselectclause, so every eventual item has to pass through three iterators. (Obviously the two where clauses could be combined in this case, but I’m making a general point.)Now compare it with the direct code:
That will run faster, because it has fewer hoops to run through. Chances are that the console output will dwarf the iterator cost though, and I’d certainly prefer the LINQ query.
EDIT: To answer about “nested foreach” loops… typically those are represented with
SelectManyor a secondfromclause:Here we’re only adding a single extra iterator, because we’d already be using an extra iterator per item in the first sequence due to the nested
foreachloop. There’s still a bit of overhead, including the overhead of doing the projection in a delegate instead of “inline” (something I didn’t mention before) but it still won’t be very different to the nested-foreach performance.This is not to say you can’t shoot yourself in the foot with LINQ, of course. You can write stupendously inefficient queries if you don’t engage your brain first – but that’s far from unique to LINQ…