Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRM SDK - Is Linq slower than QueryExpression?

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?

like image 261
aplon Avatar asked Apr 17 '14 16:04

aplon


2 Answers

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

like image 96
Scott Cramer Avatar answered Oct 21 '22 08:10

Scott Cramer


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.

like image 4
Daryl Avatar answered Oct 21 '22 06:10

Daryl