如何提高ASP.NET MVC应用程序性能?
A compiled list of possible sources of improvement are below:
General
Caching
CompiledQuery.Compile()
recursively avoiding recompilation of your query expressions OutputCacheAttribute
to save unnecessary and action executions ActionResult
methods if necessary RouteName
to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method. PartialViews
, avoid render it xxxx times: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that. Explanation And Benchmarks Routing
Use Url.RouteUrl("User", new { username = "joeuser" })
to specify routes. ASP.NET MVC Perfomance by Rudi Benkovic
Cache route resolving using this helper UrlHelperCached
ASP.NET MVC Perfomance by Rudi Benkovic
Security
DAL
Load balancing
Utilize reverse proxies, to spread the client load across your app instance. (Stack Overflow uses HAProxy ( MSDN ).
Use Asynchronous Controllers to implement actions that depend on external resources processing.
Client side
Global configuration
If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine.
ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine());
Add gzip (HTTP compression) and static cache (images, css, ...) in your web.config <system.webServer> <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/> </system.webServer>
<pages buffer="true" enableViewState="false">
The basic suggestion is to follow REST principles and the following points ties some of these principals to the ASP.NET MVC framework:
Code Climber and this blog entry provide detailed ways of increasing application's performance.
Compiled query will increase performance of your application, but it has nothing in common with ASP.NET MVC. It will speed up every db application, so it is not really about MVC.
This may seem obvious, but run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.
Not an earth-shattering optimization, but I thought I'd throw this out there - Use CDN's for jQuery, etc. .
Quote from ScottGu himself: The Microsoft Ajax CDN enables you to significantly improve the performance of ASP.NET Web Forms and ASP.NET MVC applications that use ASP.NET AJAX or jQuery. The service is available for free, does not require any registration, and can be used for both commercial and non-commercial purposes.
We even use the CDN for our webparts in Moss that use jQuery.
When accessing data via LINQ rely on IQueryable ...
Why use AsQueryable() instead of List()?
... and leverge a good Repository pattern:
Loading Subrecords in the Repository Pattern
This will optimize data access to ensure only the data needed is loaded and when only it is needed.
Also if you use NHibernate you can turn on and setup second level cache for queries and add to queries scope and timeout. And there is kick ass profiler for EF , L2S and NHibernate - http://hibernatingrhinos.com/products/UberProf . It will help to tune your queries.
I will also add:
Use Sprites : Sprites are a great thing to reduce a request. You merge all your images into a single one and use CSS to get to good part of the sprite. Microsoft provides a good library to do it: Sprite and Image Optimization Preview 4 .
Cache Your server object : If you have some references lists or data which will change rarely, you can cache them into memory instead of querying database every time.
Use ADO.NET instead of Entity Framework : EF4 or EF5
are great to reduce development time, but it will be painful to optimize. It's more simple to optimize a stored procedure than Entity Framework. So you should use store procedures as much as possible. Dapper provides a simple way to query and map SQL with very good performance.
Cache Page or partial page : MVC provides some easy filter to cache page according to some parameters, so use it.
Reduce Database calls : You can create a unique database request that returns multiple objects. Check on Dapper website.
Always have a clean architecture : Have a clean n-tiers architecture, even on a small project. It will help you to keep your code clean, and it will be easier to optimize it if needed.
You can take a look at this template " Neos-SDI MVC Template " which will create a clean architecture for you with lots of performance improvements by default (check MvcTemplate website).
In addition to all the great information on optimising your application on the server side I'd say you should take a look at YSlow . It's a superb resource for improving site performance on the client side.
This applies to all sites, not just ASP.NET MVC.
One super easy thing to do is to think asynchronously when accessing the data you want for the page. Whether reading from a web service, file, data base or something else, use the async model as much as possible. While it won't necessarily help any one page be faster it will help your server perform better overall.
1: Get Timings. Until you know where the slowdown is, the question is too broad to answer. A project I'm working on has this precise problem; There's no logging to even know how long certain things take; we can only guess as to the slow parts of the app until we add timings to the project.
2: If you have sequential operations, Don't be afraid to lightly multithread. ESPECIALLY if blocking operations are involved. PLINQ is your friend here.
3: Pregenerate your MVC Views when Publishing... That will help with some of the 'first page hit'
4: Some argue for the stored procedure/ADO advantages of speed. Others argue for speed of development of EF and a more clear seprataion of tiers and their purpose. I've seen really slow designs when SQL and the workarounds to use Sprocs/Views for data retrieval and storage. Also, your difficulty to test goes up. Our current codebase that we are converting from ADO to EF is not performing any worse (and in some cases better) than the old Hand-Rolled model.
5: That said, Think about application Warmup. Part of what we do to help eliminate most of our EF performance woes was to add a special warmup method. It doesn't precompile any queries or anything, but it helps with much of the metadata loading/generation. This can be even more important when dealing with Code First models.
6: As others have said, Don't use Session state or ViewState if possible. They are not necessarily performance optimizations that developers think about, but once you start writing more complex web applications, you want responsiveness. Session state precludes this. Imagine a long running query. You decide to open a new window and try a less complex one. Well, you may as well have waited with session state on, because the server will wait until the first request is done before moving to the next one for that session.
7: Minimize round trips to the database. Save stuff that you frequently use but will not realistically change to your .Net Cache. Try to batch your inserts/updates where possible.
7.1: Avoid Data Access code in your Razor views without a damn good reason. I wouldn't be saying this if I hadn't seen it. They were already accessing their data when putting the model together, why the hell weren't they including it in the model?
Just wanted to add my 2 cents. The MOST effective way to optimize the URL route generation in an MVC application is... not generate them at all.
Most of us more or less know how URLs are generated in our apps anyway, so simply using static Url.Content("~/Blahblah")
instead of Url.Action()
or Url.RouteUrl()
where possible, beats all other methods by almost 20 times and even more.
PS. I've ran a benchmark of couple of thousand iterations and posted results on my blog if interested.
In your clamour to optimize the client side, don't forget about the database layer. We had an application that went from 5 seconds to load up to 50 seconds overnight.
On inspection, we'd made a whole bunch of schema changes. Once we refreshed the statistics, it suddenly became as responsive as before.
Following are things to do
Using Bundling and Minification also helps you improve the performance. It basically reduces the page loading time.
If you are running your ASP.NET MVC application on Microsoft Azure (IaaS or PaaS), then do the following at least at before the first deployment.
Use the latest version of Task Parallel Library (TPL) , according to .Net version. Have to choose the correct modules of TPL for different purposes.
I did all the answers above and it just didn't solve my problem.
Finally, I solved my slow site loading problem with setting PrecompileBeforePublish in Publish Profile to true . If you want to use msbuild you can use this argument:
/p:PrecompileBeforePublish=true
It really help a lot. Now my MVC ASP.NET loads 10 times faster.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.