Improve. Net website performance

Source: Internet
Author: User
Tags net thread website performance
Collect your experience and how you can improve the performance of. Net websites

For example, use stringbuilder instead of the string connector "+ ".

A bad SQL statement can discard all your optimization work and optimize your database. This should be the top priority.
Cache is the preferred optimization tool for all web architects. This can be ranked second.

1. Database optimization. Properly design data tables based on actual conditions.
2. Page cache. Recently, the number of connections to databases has been reduced.
3. The page image cannot be too large, or use as few images as possible, Flash.
4. Use stored procedures whenever possible.

1. cache. (Technically, use a cache pool)
2. Thread Pool.
3. Image shunting.
4. A style image is combined into an image and called.
5. Div + ul + Li + CSS design webpage
6. Use less server controls. For example, the gridview can generate HTML without using the gridview

In my opinion, the real fast way for. Net websites is:
1. The front-end uses HTML for presentation, and the backend uses ashx for business logic.
2. html connects to ashx in Ajax mode to implement page data changes
Advantage: even if the network speed is slow or the efficiency of the data access layer is low, it will be blocked, making the user feel unable to wait.
This design is suitable for small and medium-sized websites with frequent page data interactions.
Obviously, this is the re-use of traditional CGI in the past. Now, many young people may not know what traditional CGI is. I have heard of the CGI of PHP.
If there are few page data interactions and only the result is, you can directly generate a pure static page.
Such a website must be fast.

1) Avoid using arraylist.
Because any object to be added to the arraylist must be of the system. Object type. When retrieving data from the arraylist, it must be split back to the actual type. We recommend that you replace arraylist with a custom set type .. NET 2.0 provides a new type called generic, which is a strong type. Using a generic set can avoid binning and unboxing and improve performance.
2) use hashtale to replace other dictionary Collection types (such as stringdictionary, namevaluecollection, and hybridcollection). You can use hashtable to store a small amount of data.
3) Declare constants for string containers. Do not enclose the characters in double quotation marks.
// Avoid
Myobject OBJ = new myobject ();
OBJ. Status = "active ";

// Recommended
Const string c_status = "active ";
Myobject OBJ = new myobject ();
OBJ. Status = c_status;

4) do not use uppercase or lowercase to convert strings and use string. Compare instead. It can be case-insensitive for comparison.

Example:
Const string c_value = "Compare ";
If (string. Compare (svariable, c_value, true) = 0)
{
Console. Write ("same ");
}

Serialize data into binary files for easy transmission.
When processing dataset and able objects, we can serialize them into XML files. If you want to transfer them over the network, XML files may cause memory, network bandwidth, and other resource problems. In this case, we can serialize it into a binary file, which will reduce the number of generated files. The Code is as follows:
Filestream FS = new filestream (@ "xmldata. bin", filemode. Create );
Binaryformatter BF = new binaryformatter ();
BF. serialize (FS, xmldata );
FS. colse ();
The generated binary file is called xmlbinary. If you open it directly with winhex, you can also see some XML tags in it. If the data volume is large, add a line of code:
Xmldata. remortingformat = serializationformat. Binary;
The generated file is called a truebinary file. when processing a large number (more than 10000 rows), the size of the generated file is one of the parts of xmlbinary. The storage mode is automatically saved during serialization, so the process of sorting is very simple. I still don't know how much performance will be lower than the performance of Directly Reading XML.
Use the datatable importrow method.
In some cases, a large amount of data needs to be copied from one able to another. The importrow method of datatable can greatly improve the performance, and there is not much difference in the amount of data, when the data volume reaches more than 10 thousand rows, it can be significantly increased by several times.

Centralized execution of SQL statements,
For example, insert into AA (name) values (''); select * Form BB;

Complex query with program execution,
For example, select * from users where name like '% ABC %'
Change to: Select * from users
Foreach datarow row in DT. Rows
If row ["name"]. Contains ("ABC ")..

For example, to dataset.
1. Accelerate row search efficiency using Indexes
If you need to search for rows repeatedly, we recommend that you add an index. There are two methods:
1) set the primarykey of the datatable.
It is applicable to row search by primarykey. Note that the datatable. Rows. Find method should be called at this time. Generally, the Select method cannot use the index.
2) use dataview
It is applicable to the case where rows are searched by non-primarykey. You can create a dataview for the able and use the sortorder parameter to indicate that the index is created. Then use find or findrows to find rows.

1. Reduce round trips)
The following method can be used to reduce the round-trip between the Web server and browser:
1. Enable cache for Browser
If the displayed content is static or has a long change period, browser cache should be enabled to avoid redundant HTTP requests.
2. Buffer page output
If possible, try to buffer the page output and send it to the client again after processing. This avoids multiple network interactions caused by frequent transmission of small pieces of content. Because the client cannot see the page content before page processing ends, if the size of a page is large, you can use the response. Flush method. This method forces the output of content in the buffer so far. You should use a reasonable algorithm to control the number of times the response. Flush method is called.

3. Use server. Transfer to redirect requests
The redirect request using the server. transfer method is better than the response. Redirect method. The reason is that response. Redirect will send a response header to broswer, pointing to the redirected URL in the Response Header, then Brower uses the new URL to re-send the request. The server. transfer method is a simple server call without these overhead!
Note that server. Transfer has limitations: First, it skips the security check; second, it is only applicable to page jumps within the same web application.

Ii. Avoid blocking and long-time jobs
If you need to run a blocking or long-running operation, you can consider using an asynchronous call mechanism so that the Web server can continue to process other requests.
1. Use Asynchronous Method to call Web Services and remote objects
As long as it is possible to avoid synchronous calls to Web Services and remote objects during request processing, because it occupies ASP. net thread pool, which will directly affect the web server's ability to respond to other requests.

2. consider adding the oneway attribute to the web method or remote object method that does not require a returned value.
This mode allows the Web server to return immediately after being called. You can decide whether to use this method based on the actual situation.

3. Use a work queue
Submit the job to the work queue on the server. The client sends a request to poll the job execution result.

Iii. Use Cache
Caching can largely determine the final performance of ASP. NET applications. Asp.net supports page output caching and partial page caching, and provides cache APIs to supply applications to cache their own data. If cache is used, consider the following points:
1. Identify data with high creation and access costs
2. Evaluate the variability of data to be cached
3. evaluation data usage frequency
4. Easy-to-change data and unchanged data separation to be cached. Only unchanged data will be cached.
5. select an appropriate cache mechanism (besides Asp.net cache, application state and session state can also be used as cache)

4. Multithreading
1. Avoid creating threads during request processing
Creating a thread during request execution is a costly operation that seriously affects the performance of the Web server. If subsequent operations must be completed by a thread, we recommend that you use the thread pool to create/manage threads.

2. Do not rely on thread data slots or static thread Variables
Because the request execution thread is a working thread in the ASP. NET thread pool, the two requests of the same client may not be processed by the same thread.

3. Avoid blocking the request processing thread

4. Avoid asynchronous calls
This is similar to 1. Asynchronous calls may lead to the creation of new threads and increase the burden on the server. Therefore, if no concurrent job is to be executed, do not execute asynchronous calls.

V. System Resources
1. Consider implementing resource pools to improve performance
2. Call dispose or close to release system resources.
3. Do not cache or occupy Resources in the resource pool for a long time
4. Apply as late as possible and release as early as possible

6. Page Processing
1. Minimize page size
Including shortening the control name, CSS class name, removing unnecessary blank lines and spaces, and disabling unwanted viewstate
2. Enable the buffer for page output)
If the buffer mechanism is disabled, use the following method.
Use a program to open the page output cache:
Response. bufferoutput = true;
Use the @ page switch to enable the page output buffer mechanism:
<% @ Page buffer = "true" %>

Use the <pages> node of the web. config or machine. config configuration file:
<Pages buffer = "true"…>
3. Optimize page output using page. ispostback
4. Improve cache efficiency and reduce rendering time by separating different content on the page
5. optimized the complex and costly cycle
6. reasonably use the computing resources of the client and transfer some operations to the client.

VII. viewstate
Viewstate is a mechanism designed by Asp.net to track status information between page backhaul by server controls.
1. Disable viewstate
If you do not need to track the page status, for example, the page does not return (PostBack), you do not need to handle server control events, or the control content is recalculated every time the page is refreshed, you do not need to use viewstate to record the page status. You can set the enableviewstate attribute for a specific webcontrol, or at the page level:
<% @ Page enableviewstate = "false" %>

2. initialize control properties at appropriate time points
ASP. the properties set by the net control during the execution of constructor and initialization are not tracked and changes to the properties are tracked after the initialization phase, and finally recorded in the _ viewstate of the IE page. Therefore, selecting a proper execution point of the initialization control attribute can effectively reduce the page size.

3. Carefully select the content to be placed in viewstate.
Content placed in viewstate will be serialized/deserialized, and Asp.net is optimized for serialization of string, integer, Boolean, and other basic types, if array, arraylist, and hashtable are used to store basic types, type converter must be provided for other types. Otherwise, a expensive binary serialization program will be used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.