I am trying to speed up an often used query. Using a CompiledQuery seemed to be the answer. But when I tried the compiled version, there was no difference in performance between the compiled and non-compiled versions.
Can someone please tell me why using Queries.FindTradeByTradeTagCompiled is not faster than using Queries.FindTradeByTradeTag?
static class Queries
{
// Pre-compiled query, as per http://msdn.microsoft.com/en-us/library/bb896297
private static readonly Func<MyEntities, int, IQueryable<Trade>> mCompiledFindTradeQuery =
CompiledQuery.Compile<MyEntities, int, IQueryable<Trade>>(
(entities, tag) => from trade in entities.TradeSet
where trade.trade_tag == tag
select trade);
public static Trade FindTradeByTradeTagCompiled(MyEntities entities, int tag)
{
IQueryable<Trade> tradeQuery = mCompiledFindTradeQuery(entities, tag);
return tradeQuery.FirstOrDefault();
}
public static Trade FindTradeByTradeTag(MyEntities entities, int tag)
{
IQueryable<Trade> tradeQuery = from trade in entities.TradeSet
where trade.trade_tag == tag
select trade;
return tradeQuery.FirstOrDefault();
}
}
Thanks to orandov, I found the answer here (at the end). If you make any changes to the query, the precompiled statement is discarded. In my case,
FirstOrDefault()was changing the underlying query.Solution was to call
AsEnumerable()on the query first. By callingAsEnumerable()the precompiled query was protected, andFirstOrDefault()was executed locally on the results (it was called againstLinq.Enumerable.FirstOrDefaultrather thanLinq.Queryable.FirstOrDefault).Net result: execution time was reduced from 45ms to 4ms. 11x faster.