Question

What is the point of using query expressions instead of lambda expressions? It not only slower it even more verbose (see here):

Example (from above link):

QE: var products = from p in northwind.Products where p.Category.CategoryName == "Beverages" select p;
LE: var products = northwind.Products.Where(p => p.Category.CategoryName == "Beverages");

Results (from above link):

QE: 00:00:00.0019557, avg. 00:00:00.0004552
LE: 00:00:00.0000574, avg. 00:00:00.0000133

Is it really worth to have 34x times slower code just for readability?

Was it helpful?

Solution

They are the same in the end.

The reason your article's test appears incredibly fast is because of deferred execution. That code isn't actually doing anything at the area they are timing. It will only do something when .ToList() is called.. or another method that forces evaluation of the query (lambda or otherwise). It's quick to interpret the query (incredibly quick, look at the times you've provided), but it's a whole other beast to actually loop over data when the query gets evaluated.

EDIT:

I just read the article. You'll notice that, according to the author, for loops are the slowest of all 3 (query expression, method syntax, for loop). This is incredibly wrong.

How can a basic for loop be thousands of times slower than a lambda? That just doesn't make sense. A loop is the most basic way of iterating over data. What do lambda's do that is so much more incredibly advanced than a loop?

...they don't. They haven't executed yet. Behold: deferred execution.

OTHER TIPS

The compiler translates query expressions into queries that use lambdas. What that means is that the two samples will compile to exactly the same code, so there can be no performance difference.

This means the benchmark you linked to is very wrong (and considering the other mistakes it does, that's not very surprising) and that you should decide between the two forms based on readability.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top