Question

More a clarity question than an actual question as I have found the solution. I just don't understand the reasoning...

Using SQLLite 3.8.3.1 Using SQLite-net 2.1

I see a distinct difference between running a .Where(lambda).FirstOrDefault() to running a .FirstOrDefault(lambda).

As far as my experience with Linq goes, database LINQ providers will treat both of these essentially the same (.FirstOrDefault(lambda) may be a little faster if it's optimized properly, but by and large, these two calls will take roughly the same time to run).

However, in SQLite-net, I am seeing the following results on a table with ~40,000 records in it:

When running .FirstOrDefault(x => x.Id == id), I am seeing the time taking on a Core-i7 to be between 2200ms to 3700ms. On a Surface RT (1st gen) this actually takes around 20,000ms-30,000ms..

When running .Where(x => x.Id == id).FirstOrDefault(), I am seeing the time taking on the same Core-i7 to be between 16ms-20ms. On a Surface RT, this takes around 30ms.

My question is whether this is just a bug, or if that's a conscious design decision. If it's a design decision - I would love to understand the reasoning behind it.

Was it helpful?

Solution

.Where is directly translated into an SQL WHERE clause, while .FirstOrDefault(lambda) reads unfiltered records from the database and then checks whether they match.

In theory, it would be possible to automatically translate the latter into the former, but in practice, this is not done. This is neither a conscious design decision nor a bug; it's simply a theoretically possible optimization has not been implemented.

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