Share tips for improving ASP. NET Web application performance

  • 2021-07-09 07:54:06
  • OfStack

In this article, I will introduce some methods and techniques to improve the performance of ASP. NET Web applications. As we all know, fixing performance problems is a tedious task, and when performance problems occur, everyone blames the developers who write the code.

How to solve the performance problem? The following are the points that should be checked as. NET developers before the application system is released.

1. debug= "false"

When creating an ASP. NET Web application, the default setting is "true". Setting it to "true" is very useful during development, but it needs to be set to "false" when the application is released and deployed.


<compilation defaultLanguage="C#" debug="false" targetFramework="4.0" /> 

2. Turn off tracing (Tracking)

tracing is very scary, have you forgotten to turn it off? If it doesn't work, make sure to edit web. config and close it. It will take up a lot of your program resources.


<trace enabled="false" requestLimit= " 10 "  pageoutput= " false "  traceMode= " SortByTime "  localOnly= " true " > 

3. Disable session

If you do not use session session tracing, be sure to disable it. You can set the following on each asp. net page:


<%@ page language="c#" codebehind="webform1.aspx.cs" autoeventwireup="false" inherits="webapplication1.webform1"

enablesessionstate="false" %> 

4. Deploy the application with the release version

When deploying an application to a production environment, be sure to use release mode, not debug mode. Request timeout is extremely easy if you use debugging templates. Deploy to the release version, and you will find a great improvement in speed.

5. Close the page's View State

View State is mainly used to echo after submission, and is only useful if the data in the page is submitted to this page. The default is "true". If you are not using form data backhaul, you can turn off View State.


<%@ Page EnableViewState="false" %> 

6. Avoid using Response. Redirect

Redirect (redirection) is cumbersome and is only used for jumping from the current physical server development to another server. Use the Server. Transfer syntax if you are only jumping within the development of this server, which will reduce many unnecessary client redirects.

7. Use the StringBuilder class and use the ToString () method

String class objects are immutable. Re-assignment of String objects essentially recreates an String object and assigns new values to it. Its method ToString does not improve performance significantly. When working with strings, it is best to use the StringBuilder class, whose. NET namespace is System. Text. Instead of creating new objects, this class directly manipulates strings through Append, Remove, Insert and so on, and returns the operation results through ToString. Its definition and operation statement are as follows


int num; 
    System.Text.StringBuilder str = new System.Text.StringBuilder(); // Create String  
    str.Append(num.ToString()); // Add numeric value num 
    Response.Write(str.ToString); // Display operation results 

8. Avoid throwing exceptions

Exceptions cause slowdown and cause the application page to display exceptions that prevent other operations. You can use try/catch to log exceptions that occur to a log file.

9. Reclaim resources using the finally method

If you are heavily using other database connections and access files in your application development, be sure to close them when you have finished using them. The finally block is the last to be executed in the program, so the code in it will ensure that 1 will be executed, and the shutdown code 1 will be executed in this development method block.

10. Validate with client-side script

Replace server development side authentication with client side authentication. Server development side data validation will consume a lot of resources on your server development, and will replace a lot of page data return.

11. Use Page. IsPostback

Make sure you don't execute too much backhaul code. Use the Page. IsPostBack property to ensure that only page initialization logic is performed when a page is loaded for the first time without postback to the responding customer.

12. Use paging

Most Web application data is displayed in tabular form. Paging has the efficiency of using application development programs. Try to display a small amount of data at a time, which will speed up the page display.

13. Use Ajax to call asynchronously

Use the Ajax method to make asynchronous calls.

14. Delete unused HttpModules

For httpModules, we can understand this as creating a generic HttpApplication event hook that can be plugged into any Web application. Using HttpModule is reusable and requires no language-specific application code, only one entry in web. config. In the web. config file, delete the unused HttpModules.

15. Avoid recursive functions/nested loops

Nested loops and recursive functions should be avoided in any programming language to improve performance.

16. Do not use unnecessary Server Control

In ASP. NET, a large number of server-side controls facilitate program development, but they may also bring performance loss, because every time users operate server-side controls, there will be a round trip with the server. Therefore, Server Control should be used less than necessary.

17. Use multithreading when calling multiple operations

When the problem occurs, the single-threaded card runs for a long time on this problem. Therefore, you can use multiple threads to improve the response speed of your application.

18. Database connection and closure

Access to database resources requires several operations: creating, opening and closing connections. These processes require multiple exchanges of information with the database for authentication and consume server resources. Connection pooling (Connection Pool) is provided in ASP. NET to improve the performance impact of opening and closing databases. The system puts the user's database connection in the connection pool, takes it out when needed, retracts the connection when closed, and waits for the next connection request. The size of the connection pool is limited, and if connections are required to be created after the maximum connection pool is reached, performance will inevitably be greatly affected. Therefore, after establishing the database connection, only when the operation is really needed, the connection is opened, and it is closed immediately after use, thus minimizing the opening time of the database connection and avoiding the situation of exceeding the connection limit.

19. Use the SqlDataReader class for fast forward-only data cursors

The SqlDataReader class provides a way to read forward-only data streams retrieved from the SQL Server database. The SqlDataReader class provides higher performance than the DataSet class if conditions allow you to use it when creating an ASP. NET application. This is the case because SqlDataReader uses the native network data transfer format of SQL Server to read data directly from the database connection. In addition, the SqlDataReader class implements the IEnumerable interface, which also allows you to bind data to server controls. For more information, see the SqlDataReader class. For information about how ASP. NET accesses data, see Accessing Data through ASP. NET.

20. High Performance SQL Statement Rules

Try to avoid full table scanning Try to avoid null value judgment of fields in where clause Try to avoid using it in where clause! = or < > Operator Try to avoid using or to join conditions in where clauses in and not in should also be used with caution Do not perform functions, arithmetic operations, or other expression operations to the left of "=" in the where clause Update statement, if only 1 or 2 fields are changed, all Update fields are not required For a large number of data (hundreds of tables are large here), JOIN should be paged first and then JOIN, otherwise the logical reading will be very high and the performance will be very poor Use varchar/nvarchar instead of char/nchar whenever possible

21. Caching

Caching is a technology that trades space for time. In popular terms, it means that the data you get is stored in memory for a period of time. In this short time, the server does not read the database or the real data source, but reads the data you store in memory. Caching is an indispensable data processing mechanism for website performance optimization, which can effectively relieve the pressure of database. The cache in ASP. NET is mainly divided into:

Page caching Data source cache Custom data cache

22. Load Balancing and Server Bonus

Load balancing should not only be regarded as a means to achieve scalability. Although it certainly improves scalability, in many cases it increases the performance of Web applications because requests and users scatter multiple servers.

23. Code review and optimization with FxCop

FxCop is a code analysis tool that uses a rule-based engine to check for non-standard parts of your code; You can also customize your own rules to add to this engine. One of the rules is:

Avoid excessive local variables Avoid using uncalled private code Avoid uninstantiated inner classes Avoid using unsealed features Avoid unnecessary casting Inline initialization of static fields of reference types Mark assemblies with NeutralResourcesLanguageAttribute Mark members as Static and so on.

24. ASP. NET Performance Monitoring Tool

These are tools for monitoring the performance of code.

. NET Memory Analyzer Red Gate ANTS Performance Analysis Tool Fiddler Performance counters

These are some tips for performance adjustment. Performance tuning is not a one-day or two-day task, but a repetitive process. For website developers, paying attention to performance issues when writing ASP. NET applications, developing good habits and improving application performance can at least delay necessary hardware upgrades and reduce the cost of websites.


Related articles: