GibboK
GibboK

Reputation: 74008

How to boost performance EF Linq to Entities

I use asp.net 4 c# and EF 4.

I'm profiling my application. I have this code which result expensive.

I woud like to know if you know a better way to write it. I need to speed it up.

            string htmlhead = context.CmsOptions.SingleOrDefault(op => op.OptionId == 7).Value;
            if (htmlhead != null)
                uxHtmlHead.Text = htmlhead;
            else
                uxHtmlHead.Text = "No Html Head.";

Thanks

Useful article http://weblogs.asp.net/zeeshanhirani/archive/2010/09/20/which-one-is-faster-singleordefault-or-firstordefault.aspx

Upvotes: 2

Views: 4269

Answers (2)

Wouter de Kort
Wouter de Kort

Reputation: 39898

There are some basic steps you can take when optimizing an Entity Framework query.

Here you can find a list of all the options.

The ones I would suggest in your case are:

  • NoTracking. You only retrieve the entity for getting a value. Not for changing it so you don't need change tracking
  • Precompile your query. This is an easy step and it really gives you a performance boost
  • Return the correct amount of data. You are selecting a whole entity just to retrieve it's value property. If you would only select the Value property less data will be returned from SQL Server (BTW, your code will throw a Null Exception if a CmsOption can't be found because of the First/Single -OrDefault part. If you really know there should be at least one entity remove the OrDefault part)

If you are using Visual Studio Premium you could put this code in a Unit Test and then profile the unit test. After each change you can compare the reports to make sure you are improving performance.

Upvotes: 1

Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13594

Use FirstOrDefault() ... This will exit as soon as it finds a result.

On the other hand SingleOrDefault() searches the entire collection for a single result and throws exception if it finds more than one result for the query

Upvotes: 13

Related Questions