How to avoid too many queries to the database in asp.net?
Among methods: static variables, viewstate, session and cache for avoiding on loading repeatedly and less making queries to the database.
What do you think the best method of the 4 above? I think cache is the best one? Or any other meth开发者_如何学编程ods better in Asp.net 3.5 or higher?
If the data being retrieved is user specific, consider using Session. If it's the same data shared among all users, consider using the cache.
I'd discourage using view state to cache database results because it quickly inflates the size of the rendered markup. On top of that, view state content must not only be downloaded but also is POSTed back to the server when the form is submitted, so with view state you pay the performance penalty twice.
Another option you didn't mention is to use the HttpContext.Items collection. This makes for a great way to cache database data per-request. This technique is quite helpful if you have many separate modules in a page (such as the master page and User Controls) that are retrieving the same data, as it allows that data to be requested once and then cached for the lifetime of that particular request. For more information, refer to HttpContext.Items - a Per-Request Cache Store.
There is no single answer to your question. A sound data-access strategy that is designed to be scalable and perform well will likely involve several or even all of the tools you mention, and possibly others.
Obviously you will not use viewState when you need persistent data throught an entire session, nor will you save per-user data in you application object.
viewState - per page
Session - per session (per user)
Application - per application
Cookie - per user (but not per session - rather throughout sessions)
You would usually use the Cache object to cache objects in application level..
That's about it.. Each has a different role.
精彩评论