ASP.NET MVC 응용 프로그램 성능을 개선하려면 어떻게합니까?
ASP.NET MVC 응용 프로그램 성능을 어떻게 개선합니까?
가능한 개선 소스 목록은 다음과 같습니다.
일반
- 프로파일 러를 사용하여 응용 프로그램의 메모리 누수 및 성능 문제를 발견하십시오. 개인적으로 나는 dotTrace를 제안합니다
- 프로덕션 환경에서는 물론 성능 프로파일 링 중에도 디버그 모드가 아닌 릴리스 모드로 사이트를 실행하십시오. 릴리스 모드가 훨씬 빠릅니다. 디버그 모드는 자체 코드에서 성능 문제를 숨길 수 있습니다.
캐싱
CompiledQuery.Compile()
쿼리 표현식의 재 컴파일을 피하면서 재귀 적으로 사용OutputCacheAttribute
불필요하고 행동적인 실행을 저장하기 위해 사용 하기 쉬운 변경하지 않는 컨텐츠 캐시- 자주 액세스하는 중요하지 않은 정보에 쿠키 사용
- ETag 및 만료 활용 -
ActionResult
필요한 경우 사용자 정의 방법 작성 - 를 사용
RouteName
하여 경로를 구성한 다음이를 사용하여 링크를 생성하고 표현식 트리 기반 ActionLink 메소드를 사용하지 마십시오. - 경로 확인 캐싱 전략 구현 고려
- 에 반복적 인 코드를 넣고 xxxx 번
PartialViews
렌더링하지 마십시오 . 동일한 뷰에서 동일한 부분을 300 번 호출하면 문제가있을 수 있습니다. 설명 및 벤치 마크
라우팅
Url.RouteUrl("User", new { username = "joeuser" })
경로를 지정하는 데 사용 합니다. ASP.NET MVC 성능 : Rudi Benkovic이 도우미 ASP.NET MVC 성능을 사용한 캐시 경로 해결
UrlHelperCached
Rudi Benkovic
보안
- 양식 인증 사용, 인증 티켓에 자주 액세스하는 중요한 데이터 유지
DAL
- LINQ를 통해 데이터에 액세스 할 때 IQueryable에 의존
- 리포지토리 패턴 활용
- 쿼리 프로파일 링 ( 예 : Uber Profiler)
- 쿼리에 대한 2 차 레벨 캐시를 고려하여 범위 및 제한 시간을 추가하십시오 (예 : NHibernate 2 차 캐시).
로드 밸런싱
리버스 프록시를 활용하여 앱 인스턴스에 클라이언트로드를 분산시킵니다. 스택 오버플로는 HAProxy ( MSDN )를 사용합니다.
외부 자원 처리에 의존하는 조치를 구현 하려면 비동기 제어기 를 사용하십시오 .
고객 입장에서
- 클라이언트 측을 최적화하고 YSlow 와 같은 도구를 사용하여 성능 향상 제안
- AJAX를 사용하여 UI 구성 요소를 업데이트하십시오. 가능하면 전체 페이지 업데이트를 피하십시오.
- 타임 아웃에 기반한 재로드에 대한 컨텐츠 전달을 위해 펍 서브 아키텍처 (예 : 혜성)를 구현하십시오.
- 가능하면 차트 및 그래프 생성 로직을 클라이언트 측으로 이동하십시오. 그래프 생성은 값 비싼 활동입니다. 클라이언트 측에 불필요한 부담을주지 않고 서버를 지연시키고 새로운 요청 (예 : Flex charting, jqbargraph , MoreJqueryCharts ) 없이 로컬로 그래프 작업을 수행 할 수 있습니다 .
- 스크립트 및 미디어 컨텐츠에 CDN을 사용하여 클라이언트 측에서로드를 개선하십시오 (예 : Google CDN )
- 작게하다 - 컴파일 - 자바 스크립트 스크립트의 크기를 개선하기 위해
- 쿠키는 모든 요청에 따라 서버로 전송되므로 쿠키 크기를 작게 유지하십시오.
- 가능하면 DNS 및 링크 프리 페치 를 사용하십시오.
글로벌 구성
Razor를 사용하는 경우 기본적으로 global.asax.cs에 다음 코드를 추가하십시오. 기본적으로 Asp.Net MVC는 aspx 엔진 및 면도기 엔진으로 렌더링합니다. 이것은 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 모듈 제거
- web.config에서 HTML을 생성하자마자 플러시하고 사용하지 않는 경우 viewstate를 비활성화하십시오.
<pages buffer="true" enableViewState="false">
기본 제안은 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 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.
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.
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.
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?
- Implement Gzip.
- Use asynchronous rendering for partial views.
- Minimize database hits.
- Use a compiled query.
- Run a profiler and find out unnecessary hits. Optimize all stored procedures which are taking more than 1 second to return a response.
- Use caching.
- Use bundling minification optimization.
- Use HTML 5 utilities like session cache and local storage for readonly contents.
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
- Kernel mode Cache
- Pipeline mode
- Remove unused modules
- runAllManagedModulesForAllRequests
- Don't write in wwwroot
- Remove unused view engines and language
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.
- 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.
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.
참고URL : https://stackoverflow.com/questions/2246251/how-do-i-improve-asp-net-mvc-application-performance
'Programing' 카테고리의 다른 글
arguments.callee.caller 속성이 JavaScript에서 더 이상 사용되지 않는 이유는 무엇입니까? (0) | 2020.04.30 |
---|---|
HTML 버튼을 사용하여 JavaScript 함수 호출 (0) | 2020.04.30 |
루트 액세스없이 파이썬 모듈을 설치하는 방법은 무엇입니까? (0) | 2020.04.30 |
Java 8 스트림의 .min () 및 .max () : 왜 컴파일됩니까? (0) | 2020.04.30 |
dyld : 라이브러리가로드되지 않았습니다… 이유 : 이미지를 찾을 수 없습니다 (0) | 2020.04.30 |