Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to entities is very slow using .Take() method

I have a table of 200,000 record where I am getting only the top 10 using .Take() but it is taking about 10 seconds to get the data.

My question is: does the .Take() method get all the data from the database and filter the top 10 on the client side?

Here is my code:

mylist = (from mytable in db.spdata().OrderByDescending(f => f.Weight)
                                    group feed by mytable.id into g
                                    select g.FirstOrDefault()).Take(10).ToList();

spdata() is a function Import from stored procedure.

Thanks

like image 258
Alex Avatar asked Dec 18 '12 13:12

Alex


People also ask

How to improve LINQ query performance?

Before we get into how we can improve LINQ query performance, let’s first try to understand the various steps involved in a LINQ query execution. All LINQ queries are first converted to SQL statements. This conversion also involves checking of LINQ query syntaxes and translating the queries to SQL.

How much slower is LINQ with no compilation?

It can lead to a lot of wrong conclusions as there is a lot of noise associated with the first run. The subsequent readings have the real meat difference. The average difference between them is 5 times. In other words, a LINQ query executed using no compilation is 5 ms slower than compiled LINQ queries.

How does LINQ work with static classes?

As we all know, a static class is a global cache. So LINQ uses the query plan from the static class object rather than building and preparing the query plan from scratch. In all, there are four steps which need to be performed right from the time LINQ queries are built till they are fired.

What is compiled LINQ?

So LINQ uses the query plan from the static class object rather than building and preparing the query plan from scratch. In all, there are four steps which need to be performed right from the time LINQ queries are built till they are fired. By using compiled LINQ queries, the four steps are reduced to two.


Video Answer


1 Answers

The stored procedure probably returns a lot of data to the client which is very slow. You cannot remote a query to an sproc. That would be possible using a view or a table-valued function.

There's no way to use an sproc in a query. You can only execute it by itself.

Your intention probably was to execute the Take(10) on the server. For that to work you need to switch to an inline query, a view or a TVF.

like image 129
usr Avatar answered Sep 20 '22 10:09

usr