CRM SDK - Is Linq slower than QueryExpression?
Asked Answered
H

2

5

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?

Hawkbill answered 17/4, 2014 at 16:7 Comment(0)
L
5

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

Linker answered 21/8, 2014 at 0:46 Comment(2)
Thanks for the response. However my doubt is regarding the execution time of a linq Query versus a QueryExpression. Say that in both cases I return all fields (or for that matter, in both cases I return only 1 field). Which Query should be faster?Hawkbill
The first part of Daryl's answer addresses this question (of which is faster given equivalent "select" statements)Leucoderma
M
4

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.

Myeloid answered 30/9, 2015 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.