开发者

AsQueriable() or Expression<T>.Compile()?

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)?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜