views:

105

answers:

3

Edit2:
After finally being able to profile the two against each other, it appears that in my situation .AsQueryable() is slightly faster than Expression.Compile().

Original question:
I have implemented a cache of some database tables (as List<T>) that I need to query with the same Expression<Func<T, bool>> as I would use when querying against the Table<T> itself.

What is the fastest/best way of these:

List<T>.AsQueryable().FirstOrDefault(Expression<Func<T, bool>>)

or

List<T>.FirstOrDefault(Expression<Func<T, bool>>.Compile())

?

Edit: Changed Where to FirstOrDefault, as that is the method I'm using. I guess I was a little tired when I wrote the question. Will FirstOrDefault examine every item once like Where, or does it actually stop on the first hit (if any)?

+1  A: 

Depends on how many operations you're going to execute, and the processor-intensity of your expression execution.

You can easily test this using a stopwatch or some other diagnostic component.

Jan Jongboom
+1  A: 

Why second guess it? Profile it with your data and see which works best.

Winston Smith
+1  A: 

As always, the best way to determine what's faster is to try it out, however:

Filtering a List<> using a simple Where will always result in each item being examined once. Without further assumptions such as your list being sorted in a specific order, there's really no other way, meaning the two versions you give will result in the exact same evaluations of your expression.

If you're going to use the same expression multiple times, you could possibly benefit from compiling it and caching the delegate, though the data would have to be small and the expression complex in order for it to make a difference.

Edit: Going through Queryable could possibly be faster for expressions that does not actually depend on any input at all, such as () => false.

Freed
Does switching from Where to FirstOrDefault change anything? My List<> are just a Table<>.ToList() so they are just copies of the tables from SQL. The queries are very simple, just a couple of input parameter compared to column value string comparisons anded together.
Sub-Star