如何提高ASP ?NET MVC应用程序性能?
这不是一个惊天动地的优化,但我想我要把它扔在那里-使用CDN的jQuery,等等。
引用ScottGu自己的话:微软Ajax CDN使你能够显著提高ASP的性能。NET Web Forms和ASP。asp.net MVC应用程序使用ASP。NET AJAX或jQuery。这项服务是免费的,不需要任何注册,可以用于商业和非商业目的。
我们甚至使用CDN为我们的web部件在Moss使用jQuery。
基本的建议是遵循REST原则,以下几点将这些原则中的一些与ASP。NET MVC框架:
Make your controllers stateless - this is more of a 'Web performance / scalability' suggestion (as opposed to micro/machine level performance) and a major design decision that would affect your applications future - especially in case it becomes popular or if you need some fault tolerance for example. Do not use Sessions Do not use tempdata - which uses sessions Do not try to 'cache' everything 'prematurely'. Use Forms Authentication Keep your frequently accessed sensitive data in the authentication ticket Use cookies for frequently accessed non sensitive information Make your resources cachable on the web Utilize ETags Use expiration Write your custom ActionResult classes if necessary Utilize reverse proxies Compile your JavaScript. There is Closure compiler library to do it as well (sure there are others, just search for 'JavaScript compiler' too) Use CDNs (Content Delivery Network) - especially for your large media files and so on. Consider different types of storage for your data, for example, files, key/value stores, etc. - not only SQL Server Last but not least, test your web site for performance
Code Climber和这篇博客文章提供了提高应用程序性能的详细方法。
编译后的查询将提高应用程序的性能,但它与ASP没有任何共同之处。净MVC。它将加速每一个db应用程序,所以它不是真正的MVC。
当通过LINQ访问数据依赖IQueryable…
为什么使用AsQueryable()而不是List()?
... 并利用一个好的存储库模式:
在存储库模式中加载子记录
这将优化数据访问,以确保只加载需要的数据。
以下是可能的改进来源:
一般
利用分析器来发现应用程序中的内存泄漏和性能问题。我个人建议dotTrace 在生产环境和性能分析期间,以发布模式(而不是调试模式)运行站点。释放模式要快得多。调试模式可以在您自己的代码中隐藏性能问题。
缓存
Use CompiledQuery.Compile() recursively avoiding recompilation of your query expressions Cache not-prone-to-change content using OutputCacheAttribute to save unnecessary and action executions Use cookies for frequently accessed non sensitive information Utilize ETags and expiration - Write your custom ActionResult methods if necessary Consider using the RouteName to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method. Consider implementing a route resolution caching strategy Put repetitive code inside your 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
路由
使用Url。RouteUrl("User", new {username = "joeuser"})指定路由。ASP。NET MVC性能由Rudi Benkovic编写 缓存路由解析使用这个助手UrlHelperCached ASP。NET MVC性能由Rudi Benkovic编写
安全
使用表单身份验证,将您经常访问的敏感数据保存在 身份验证票
DAL
当通过LINQ访问数据时,依赖于IQueryable 利用存储库模式 配置您的查询,即优步Profiler 考虑二级缓存,为你的查询添加一个范围和一个超时,即NHibernate二级缓存
负载平衡
利用反向代理,在应用实例中分散客户端负载。Stack Overflow使用HAProxy (MSDN)。 使用异步控制器来实现依赖于外部资源处理的操作。
客户端
Optimize your client side, use a tool like YSlow for suggestions to improve performance Use AJAX to update components of your UI, avoid a whole page update when possible. Consider implement a pub-sub architecture -i.e. Comet- for content delivery against reload based in timeouts. Move charting and graph generation logic to the client side if possible. Graph generation is a expensive activity. Deferring to the client side your server from an unnecessary burden, and allows you to work with graphs locally without make a new request (i.e. Flex charting, jqbargraph, MoreJqueryCharts). Use CDN's for scripts and media content to improve loading on the client side (i.e. Google CDN) Minify -Compile- your JavaScript in order to improve your script size Keep cookie size small, since cookies are sent to the server on every request. Consider using DNS and Link Prefetching when possible.
全局配置
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> Remove unused HTTP Modules Flush your HTML as soon as it is generated (in your web.config) and disable viewstate if you are not using it <pages buffer="true" enableViewState="false">
另外,如果你使用NHibernate,你可以为查询打开和设置二级缓存,并添加到查询范围和超时。并且有踢屁股的EF, L2S和NHibernate分析器- http://hibernatingrhinos.com/products/UberProf。这将有助于调优您的查询。
除了所有关于在服务器端优化应用程序的重要信息外,我还想说你应该看看YSlow。它是提高客户端站点性能的极好的资源。
这适用于所有网站,而不仅仅是ASP。净MVC。
一件非常简单的事情是在访问页面所需的数据时进行异步思考。无论是从web服务、文件、数据库还是其他东西读取,都尽可能使用异步模型。虽然它不一定会帮助任何一个页面更快,但它会帮助您的服务器整体性能更好。
我还要补充一点:
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).
1:获取时间。在你知道放缓在哪里之前,这个问题太宽泛了,无法回答。我正在做的一个项目就有这样的问题;没有日志记录,甚至不知道某些事情需要多长时间;在我们将计时添加到项目中之前,我们只能猜测应用程序的慢部分。
2:如果你有顺序操作,不要害怕轻度多线程。特别是当涉及到阻塞操作时。PLINQ是你的朋友。
3:在发布时预生成MVC视图这将有助于一些“第一页点击”
4:有些人认为存储过程/ADO在速度上有优势。其他人则主张加快英孚教育的发展速度,并对教育层级及其目的进行更明确的划分。我曾见过SQL和使用scpros /Views进行数据检索和存储的变通方法时非常缓慢的设计。同时,你的测试难度也会增加。我们目前正在从ADO转换到EF的代码库的性能并不比旧的手卷模型差(在某些情况下更好)。
5:也就是说,考虑一下应用程序的预热。我们所做的帮助消除大部分EF性能问题的部分工作是添加一个特殊的预热方法。它不预编译任何查询或任何东西,但它有助于大量元数据的加载/生成。在处理Code First模型时,这一点可能更加重要。
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:最小化到数据库的往返。保存你经常使用但实际上不会更改到. net缓存的东西。在可能的情况下尝试批处理插入/更新。
7.1:避免数据访问代码在你的Razor视图没有一个该死的好理由。要不是亲眼所见,我也不会这么说。在构建模型时,他们已经在访问数据了,为什么他们不把数据包括在模型中呢?
在您嚷嚷着优化客户端时,不要忘记数据库层。我们有一个应用程序在一夜之间从5秒加载到50秒。
在检查中,我们做了一大堆模式更改。一旦我们刷新统计数据,它突然变得像以前一样灵敏。
Gzip实现。 对部分视图使用异步呈现。 最小化数据库命中次数。 使用编译后的查询。 运行分析器找出不必要的匹配。优化所有返回响应时间超过1秒的存储过程。 使用缓存。 使用捆绑最小化优化。 对只读内容使用会话缓存和本地存储等HTML 5实用程序。
以下是要做的事情
内核模式缓存 管道模式 移除未使用的模块 runAllManagedModulesForAllRequests 不要使用wwwroot 删除未使用的视图引擎和语言
只是想说说我的意见。优化MVC应用程序中URL路由生成的最有效的方法是…根本不产生它们。
我们大多数人或多或少都知道url是如何在我们的应用程序中生成的,所以只要使用静态Url.Content(“~/Blahblah”)而不是Url.Action()或Url.RouteUrl(),就可以胜过所有其他方法近20倍甚至更多。
PS:我已经运行了几千次迭代的基准测试,如果有兴趣的话可以在我的博客上发布结果。
如果您正在运行您的ASP。NET MVC应用程序在Microsoft Azure (IaaS或PaaS)上,然后至少在第一次部署之前执行以下操作。
Scan your code with static code analyzer for any type of code debt, duplication, complexity and for security. Always enable the Application Insight, and monitor the performance, browsers, and analytics frequently to find the real-time issues in the application. Implement Azure Redis Cache for static and less frequent change data like Images, assets, common layouts etc. Always rely on APM (Application Performance Management) tools provided by Azure. See application map frequently to investigate the communication performance between internal parts of the application. Monitor Database/VM performance too. Use Load Balancer (Horizontal Scale) if required and within the budget. If your application has the target audience all over the globe, then use Azure Trafic Manager to automatically handle the incoming request and divert it to the most available application instance. Try to automate the performance monitoring by writing the alerts based on low performance.
我做了上面所有的答案,但还是没有解决我的问题。
最后,我解决了我的网站加载缓慢的问题,在发布配置文件PrecompileBeforePublish设置为真。如果你想使用msbuild,你可以使用这个参数:
/p:PrecompileBeforePublish=true
这真的很有帮助。现在我的MVC ASP。NET加载速度快10倍。
推荐文章
- 在哪里放置AutoMapper.CreateMaps?
- String类中的什么方法只返回前N个字符?
- 如何在HTML5中改变视频的播放速度?
- 我如何提高ASP。NET MVC应用程序性能?
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- Visual Studio弹出提示:“操作无法完成”
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间
- 如何在剃刀视图上引用.css文件?
- 由Jon Skeet撰写的《Singleton》澄清
- 自定义数字格式字符串始终显示符号
- 列表推导式和函数式函数比for循环更快吗?
- Post参数始终为空
- string.ToLower()和string.ToLowerInvariant()