I've searched around a lor to figure this one out and still can't see a good response. I timed the same query using Linq and QueryExpression and generally the later comes out much faster. However for the many reasons exposed in multiple posts (including the fact than QueryExpression syntax is horrible), I prefer to use Linq.
Can anyone provide an explanation as to why the query in QE is faster than Linq? Would this be an environmental problem (VS 2012, CRM 2011 and 2013, Windows 7, etc., i.e., pretty standard) or by design/arquitecture is QE faster than Linq?
Because the query does not know what fields will be needed later, all columns are returned from the entity when only the entity is specified in the select clause. In order to specify only the fields you will use, you must return a new object in the select clause, specifying the fields you want to use.
So instead of this:
var accounts = from acct in xrm.AccountSet
where acct.Name.StartsWith("Test")
select acct;
Use this:
var accounts = from acct in xrm.AccountSet
where acct.Name.StartsWith("Test")
select new Account()
{
AccountId = acct.AccountId,
Name = acct.Name
};
Check out this post more details.
To Linq or not to Linq
The LINQ to CRM Provider has to convert the LINQ Expression to a Query Expression
before it sends the request to the server, so a LINQ query is always going to be slower since it has to generate the QueryExpression
first.
As Scott points out in his answer, it is also easy to not realize that you're querying all fields for an entity when using LINQ. That would make it even slower since the generated QueryExpression
is less optimized than an explicitly defined one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With