如何提高 ASP.NET MVC 应用程序的性能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2246251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:53:45  来源:igfitidea点击:

How do I improve ASP.NET MVC application performance?

.netasp.net-mvcperformanceiis

提问by SDReyes

How do you improve your ASP.NET MVC application performance?

您如何提高 ASP.NET MVC 应用程序的性能?

回答by George Stocker

A compiled list of possible sources of improvement are below:

可能的改进来源的汇编列表如下:

General

一般的

  • Make use of a profiler to discover memory leaks and performance problems in your application. personally I suggest dotTrace
  • 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.
  • 使用分析器来发现应用程序中的内存泄漏和性能问题。我个人建议dotTrace
  • 在生产和性能分析期间,以发布模式而非调试模式运行您的站点。释放模式要快得多。调试模式可以在您自己的代码中隐藏性能问题。

Caching

缓存

  • Use CompiledQuery.Compile()recursively avoiding recompilation of your query expressions
  • Cache not-prone-to-change content using OutputCacheAttributeto save unnecessary and action executions
  • Use cookies for frequently accessed non sensitive information
  • Utilize ETagsand expiration - Write your custom ActionResultmethods if necessary
  • Consider using the RouteNameto 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 xxxxtimes: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that. Explanation And Benchmarks
  • 使用CompiledQuery.Compile()递归避免重新编译查询表达式
  • 缓存不易更改的内容,OutputCacheAttribute用于保存不必要的和动作执行
  • 将 cookie 用于经常访问的非敏感信息
  • 利用ETags和到期 -ActionResult如有必要,编写自定义方法
  • 考虑使用RouteName来组织您的路由,然后使用它来生成您的链接,并尽量不要使用基于表达式树的 ActionLink 方法。
  • 考虑实施路由解析缓存策略
  • 将重复的代码放入您的 中PartialViews,避免将其渲染xxxx次:如果您最终在同一个视图中调用相同的部分 300 次,则可能有问题。解释和基准

Routing

路由

Security

安全

  • Use Forms Authentication, Keep your frequently accessed sensitive data in the authentication ticket
  • 使用表单身份验证,将您经常访问的敏感数据保存在身份验证票中

DAL

达尔文

Load balancing

负载均衡

  • Utilize reverse proxies, to spread the client load across your app instance. (Stack Overflow uses HAProxy(MSDN).

  • Use Asynchronous Controllersto implement actions that depend on external resources processing.

  • 利用反向代理,将客户端负载分散到您的应用程序实例中。(堆栈溢出使用HAProxy( MSDN)。

  • 使用异步控制器来实现依赖于外部资源处理的动作。

Client side

客户端

  • Optimize your client side, use a tool like YSlowfor 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 Prefetchingwhen possible.
  • 优化你的客户端,使用像YSlow这样的工具来获取提高性能的建议
  • 使用 AJAX 更新 UI 组件,尽可能避免更新整个页面。
  • 考虑实现发布-订阅架构 - 即 Comet- 用于基于超时的重新加载内容交付。
  • 如果可能,将图表和图形生成逻辑移至客户端。图生成是一项昂贵的活动。将您的服务器从不必要的负担推迟到客户端,并允许您在本地处理图形而无需发出新请求(即 Flex 图表、jqbargraphMoreJqueryCharts)。
  • 将 CDN 用于脚本和媒体内容以改善客户端的加载(即Google CDN
  • 缩小 -编译- 您的 JavaScript 以改善您的脚本大小
  • 保持 cookie 的大小,因为每次请求都会将 cookie 发送到服务器。
  • 如果可能,请考虑使用DNS 和链接预取

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>

  • 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">
  • 如果使用 Razor,请在 global.asax.cs 中添加以下代码,默认情况下,Asp.Net MVC 使用 aspx 引擎和 razor 引擎呈现。这仅使用 RazorViewEngine。

    ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine());

  • 在 web.config 中添加 gzip(HTTP 压缩)和静态缓存(图像、css 等) <system.webServer> <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/> </system.webServer>

  • 删除未使用的 HTTP 模块
  • 生成 HTML 后立即刷新它(在您的 web.config 中),如果您不使用它,则禁用视图状态 <pages buffer="true" enableViewState="false">

回答by ziya

The basic suggestion is to follow REST principlesand the following points ties some of these principals to the ASP.NET MVC framework:

基本建议是遵循REST 原则,以下几点将其中一些原则与 ASP.NET MVC 框架联系起来:

  1. Make your controllers stateless- this is more of a 'Webperformance / 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'.
  2. Use Forms Authentication
    • Keep your frequently accessed sensitive data in the authentication ticket
  3. Use cookies for frequently accessed non sensitive information
  4. Make your resources cachableon the web
  5. Compile your JavaScript. There is Closure compiler libraryto do it as well (sure there are others, just search for 'JavaScript compiler'too)
  6. Use CDNs (Content Delivery Network) - especially for your large media files and so on.
  7. Consider different types of storage for your data, for example, files, key/value stores, etc. - not only SQL Server
  8. Last but not least, test your web site for performance
  1. 使您的控制器无状态- 这更像是一个“ Web性能/可扩展性”建议(与微/机器级性能相反)和一个会影响您的应用程序未来的主要设计决策 - 特别是在它变得流行或如果您需要一些例如容错。
    • 不要使用会话
    • 不要使用临时数据 - 它使用会话
    • 不要试图“过早地”“缓存”所有内容。
  2. 使用表单身份验证
    • 将您经常访问的敏感数据保存在身份验证票中
  3. 将 cookie 用于经常访问的非敏感信息
  4. 使您的资源可在网络上 缓存
  5. 编译你的 JavaScript。也有 Closure 编译器库可以做到这一点(当然还有其他的,只需搜索“JavaScript 编译器”
  6. 使用 CDN(内容交付网络)——尤其是对于您的大型媒体文件等。
  7. 考虑不同类型的数据存储,例如文件、键/值存储等 - 不仅是 SQL Server
  8. 最后但并非最不重要的是,测试您的网站的性能

回答by LukLed

Code Climberand this blog entryprovide detailed ways of increasing application's performance.

Code Climber此博客条目提供了提高应用程序性能的详细方法。

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.

编译查询将提高应用程序的性能,但它与 ASP.NET MVC 没有任何共同之处。它会加速每个 db 应用程序,所以它不是真的关于 MVC。

回答by Craig Stuntz

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 muchfaster. Debug mode can hide performance problems in your own code.

这可能看起来很明显,但是在生产环境以及性能分析期间,请在发布模式而不是调试模式下运行您的站点。释放模式快得多。调试模式可以在您自己的代码中隐藏性能问题。

回答by Keith Adler

When accessing data via LINQ rely on IQueryable ...

通过 LINQ 访问数据时,依赖 IQueryable ...

Why use AsQueryable() instead of List()?

为什么使用 AsQueryable() 而不是 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.

这将优化数据访问,以确保仅加载需要的数据,并且仅在需要时加载。

回答by Ta01

Not an earth-shattering optimization, but I thought I'd throw this out there - Use CDN's for jQuery, etc..

不是惊天动地的优化,但我想我会把它扔在那里 -使用 CDN 的 jQuery 等

Quote from ScottGu himself: The Microsoft Ajax CDNenables 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.

引用 ScottGu 本人的话:Microsoft Ajax CDN使您能够显着提高使用 ASP.NET AJAX 或 jQuery 的 ASP.NET Web 窗体和 ASP.NET MVC 应用程序的性能。该服务免费提供,无需任何注册,可用于商业和非商业目的。

We even use the CDN for our webparts in Moss that use jQuery.

我们甚至在使用 jQuery 的 Moss 中为我们的 webpart 使用 CDN。

回答by zihotki

Also if you use NHibernateyou 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.

此外,如果您使用NHibernate,您可以为查询打开和设置二级缓存,并添加到查询范围和超时。还有适用于EF、L2S 和 NHibernate 的踢屁股分析器- http://hibernatingrhinos.com/products/UberProf。这将有助于调整您的查询。

回答by Jeff Lequeux

I will also add:

我还要补充:

  1. 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.

  2. 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.

  3. Use ADO.NET instead of Entity Framework: EF4 or EF5are great to reduce development time, but it will be painful to optimize. It's more simple to optimize a stored procedurethan 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.

  4. Cache Page or partial page: MVC provides some easy filter to cache page according to some parameters, so use it.

  5. Reduce Database calls: You can create a unique database request that returns multiple objects. Check on Dapper website.

  6. 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.

  7. 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 MvcTemplatewebsite).

  1. 使用精灵:精灵是减少请求的好东西。您将所有图像合并为一个,并使用 CSS 获得精灵的重要部分。微软提供了一个很好的库来做到这一点: Sprite and Image Optimization Preview 4

  2. 缓存您的服务器对象:如果您有一些很少更改的引用列表或数据,您可以将它们缓存到内存中,而不是每次都查询数据库。

  3. 使用 ADO.NET 而不是 Entity FrameworkEF4 or EF5可以很好地减少开发时间,但是优化起来会很痛苦。优化存储过程比实体框架更简单。所以你应该尽可能地使用存储过程。Dapper 提供了一种简单的方式来查询和映射 SQL,性能非常好。

  4. 缓存页面或部分页面:MVC 提供了一些简单的过滤器来根据一些参数缓存页面,所以使用它。

  5. 减少数据库调用:您可以创建一个返回多个对象的唯一数据库请求。检查 Dapper 网站。

  6. 始终有一个干净的架构:即使在一个小项目中,也有一个干净的 n 层架构。它将帮助您保持代码整洁,并且在需要时可以更轻松地对其进行优化。

  7. 您可以看看这个模板“ Neos-SDI MVC 模板”,它将为您创建一个干净的架构,默认情况下有很多性能改进(查看MvcTemplate网站)。

回答by Steve

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.

除了关于在服务器端优化应用程序的所有重要信息之外,我想说您应该看看YSlow。它是提高客户端站点性能的极好资源。

This applies to all sites, not just ASP.NET MVC.

这适用于所有站点,而不仅仅是 ASP.NET MVC。

回答by No Refunds No Returns

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.

一件非常简单的事情就是在访问页面所需的数据时进行异步思考。无论是从 web 服务、文件、数据库还是其他东西中读取,都尽可能使用异步模型。虽然它不一定会帮助任何一页更快,但它会帮助您的服务器整体性能更好。