Search code examples
asp.net-mvc-3linqfiddlerperformance-testing

make better LinQ queries mvc3


I had a question in my mind, to get the better performance of a linq query , is it better to use the select extension to select just the fields we need, not the whole fields?!!!

I have a table "News" and it has fileds ( id, title, text, regtime,regdate,username,...) which the text field is very long text and it has to have a big size for each row. so i decided to change this query in the index page which does not show the text of news from this

var model=db.News.ToList();

to this one

var model=db.News.Select(n=>new NewsVM(){ id=r.id, title=r.title, regtime=r.regtime,...});

and i fiddler both queries and the Bytes Received was the same


Solution

  • Fiddler doesn't monitor the data sent from the Sql Server to the webserver. Fiddler will only show you the size of the HTML that the view generates.

    So to answer your question, YES! The performance is much better if you ask only for the fields you need rather than either asking for all of them, or blindly using the select method. The Sql Server should/may run the query faster. It may be able to retrieve all the fields you are asking for directly from an index rather than having to actually read each row. There are many other reasons as well, but they get more technical.

    As for the webserver, it too will execute faster since it doesn't have to recieve as much data from the sql server, and it will use less memory (leaving more memory available for caching, etc).

    A good analogy would be asking if I ask you for the first word of the first 10 books in your library, would it be faster if you had to copy the entire content of each book to your notebook first, then give me the first word, or if it would be faster if you just wrote down the first word of each book. Both answers are only 10 words long.