ASP. NET Website performance improvement-CPU

Source: Internet
Author: User
Identify bottlenecks

Multiple technologies can identify high CPU usageCode:

    • Focus on frequently executed code. Special attention should be paid to loops, especially nested loops. If the class inherited from icomparable is used for sorting, this code will be executed very frequently. If you obtain data from the database, each row of data must be processed, and this will also use a loop.
    • You can use a lightweight counter to measure the execution frequency and execution time.
    • Old-fashioned debugging. Perform stress tests on the website, which will use a lot of CPU. Half of the Code is reduced. If the CPU usage is much reduced, the problem may be the half of the reduced code. Continue until the problematic code is found.
    • Try to changeAlgorithm.

You can use the stopwatch class to calculate the code execution time:

 
Using system. diagnostics; stopwatch = new stopwatch (); stopwatch. start (); // first bit of code... stopwatch. stop (); timespan elapsedtime1 = stopwatch. elapsed; stopwatch. reset (); stopwatch. start (); // second bit of code... stopwatch. stop (); timespan elapsedtime2 = stopwatch. elapsed;
Tools

Sometimes, the bottleneck is hidden deeply, which requires analysis tools. These tools reduce the website's running speed, so they are not used in the development environment.

    • Visual Studio performance profilling: it can analyze the memory occupied by each method, average execution time, and call frequency. Another great feature is hotpathing, which shows which code takes a lot of time for execution. Complete documentation: http://msdn.microsoft.com/en-us/library/z9z62c29.aspx.
    • Ants performance profiler: http://www.red-gate.com/products/ants_cece_profiler /.
    • Eqatec profiler: http://www.eqatec.com/tools/profiler /.
    • Slimtune: http://code.google.com/p/slimtune /.
Data Access Connection Pool

Opening a database connection is expensive. Therefore, ASP. NET maintains a connection pool. Each connection string has a connection pool.

When a connection is opened, a connection is obtained from the connection pool. When the connection is closed, it is still open and the connection pool is returned to be used by another thread.

For each database to be accessed, only one connection string is used.

Store the connection string in Web. config:

<Configuration> <connectionstrings> <Add name = "connectionstring" connectionstring = "..."/> </connectionstrings> </configuration>

Obtain the connection string in the Code:

 
Using system. configuration;... string connectionstring = configurationmanager. connectionstrings ["connectionstring"]. connectionstring;

The connection pool is controlled by connection string parameters:

Max pool size: the maximum value of the connection pool. The default value is 100. If the connection pool reaches the maximum value, connection requests will be queued.

Min pool size: the initial number of connections when the connection pool is created. The default value is 0. In this way, the initial database access will be delayed because a new connection is created. To reduce latency, you can set the parameter to the expectedProgramThe final number of connections required.

Connect Timeout: the time when the request waits for the connection before terminating and generating an error. The unit is seconds. The default value is 15 seconds.

Pooling: whether to use the connection pool. The default value is true. Set to false to disable the connection pool.

Why should I close the connection pool? This is to crash when the application connection leaks.

Consider the following code:

 
Sqlconnection connection = new sqlconnection (connectionstring); connection. open ();... code that may throw an exception... connection. Close ();

If the code throws an exception, the connection will not be closed. Eventually, it will be disabled by the garbage collector, but it will take some time, depending on the memory pressure. At the same time, more and more connections will be added to the connection pool.

When the maximum value of the connection pool is reached, the request waits until the connection times out and is terminated.

The best way is to modify the code so that the connection will be closed even if an exception occurs:

 

Using (sqlconnection connection = new sqlconnection (connectionstring) {connection. open ();... code that may throw an exception ...}
 
Use the counter to observe the number of currently opened connections. if the traffic is stable, the number of connections continues to increase, indicating that connection leaks may occur.
 
Category: SQL Server General Statistics
User connections: Number of users currently connected to the system.
Dataset and list

When reading data from a database, you may need to store the data in the collection. In this way, you can cache or pass it to another layer.

The simplest set is dataset, which can be filled with only a small amount of code, and dataset has many built-in functions. Another option is generic list, which requires self-filling and does not have many built-in functions, but it is lightweight.

If you do not need the functions provided by dataset, you can use a generic list to save the visible CPU cycle.

Returns multiple result sets.

Ado. Net allows multiple result sets to be obtained at a time. For example:

 
Create procedure [DBO]. [getbooksandauthors] asbegin set nocount on; select [bookid], [title], [authorid], [price] from [DBO]. [Book] select [authorid], [name], [address], [PHONE], [email] from [DBO]. [author] End
 
 
Use sqldatareader. nextresult to access the second result set:
 
 
Using (sqldatareader reader = cmd. executereader () {While (reader. read () {// read first result set ...} reader. nextresult (); While (reader. read () {// read Second result set ...}}
 
 
 
If multiple result sets need to be displayed on one page, you can read them at a time.
Multiple insert statements are sent in one connection.

When you insert data in batches, You can execute multiple insert statements at a time.

Create SQL parameters:

Const string singleexec = "Exec DBO. insertdata @ title {0}, @ author {0}, @ price {0}; "; stringbuilder SQL = new stringbuilder (); For (Int J = 0; j <nbrinserts; j ++) {SQL. appendformat (singleexec, J );}
 
Assign values to parameters:
For (Int J = 0; j <nbrinserts; j ++) {cmd. parameters. addwithvalue ("@ title" + J. tostring (),...); cmd. parameters. addwithvalue ("@ Author" + J. tostring (),...); cmd. parameters. addwithvalue ("@ price" + J. tostring (),...);} then send all exec statements in one go to the database: cmd. commandtype = commandtype. text; cmd. executenonquery ();

Note that command text includes SQL text (Exec statement) instead of stored procedure name. So commandtype. Text is used.

Use native data providers

Use native data providers, such as system. data. sqlclient or system. data. oracleclient, instead of using system. data. oledb and system. data. ODBC, because native data providers are less abstract, it is more efficient,

Exception

Throwing an exception is very expensive. When you throw an exception, you must first create an exception object on the stack. The exception object must include the call stack, which is created at the runtime. Then, find the appropriate exception processor during running and execute it. Finally, run the finally code block. Use exceptions only when exceptions occur. Do not use exceptions in normal program processes.

Counter

Category: Net CLR exceptions

# Of exceps thrown: number of exceptions thrown from program startup.

# Of exceps thrown/sec: number of exceptions thrown per second.

# Of filters/sec: Number of. Net exception filters executed per second. The exception filter determines whether exceptions should be handled.

# Of finallys/sec: The Finally block executed per second.

Throw to catch depth/sec: stack frame between frames that throw an exception and frames that handle the exception per second.

Databinder. Eval

For example, the controls of the gridview and repeater Use templates. The common method is to use databinder. Eval in the template to reference the field:

 
<Asp: repeater id = "rptreval" runat = "server"> <itemtemplate> <% # eval ("field1") %> <% # eval ("field2 ") %> <% # eval ("field3") %> <% # eval ("field4") %> </itemtemplate> </ASP: repeater>

This method uses reflection. If there are 10 rows and 4 fields in each line, the eval is executed for 40 times.

The faster method is to directly reference the class containing fields:

<Asp: repeater id = "rptrcast" runat = "server">
<Itemtemplate>
<% # (Myclass) container. dataitem). field1 %>
<% # (Myclass) container. dataitem). field2 %>
<% # (Myclass) container. dataitem). field3 %>
<% # (Myclass) container. dataitem). field4 %>
</Itemtemplate>
</ASP: repeater>

If datatable is used, it is forcibly converted to datarowview.

Garbage Collection

Use the % time in GC calculator in the. net clr memmory classification to view the time occupied by garbage collection.

Thread

If the thread is abused, many CPU cycles may be wasted. If your program is multi-threaded, consider the following methods to reduce thread consumption:

    • If a thread is used to wait for resources such as databases or Web Services, asynchronous requests may be used.
    • Do not create a thread by yourself. Use threadpool. queueuserworkitem to obtain a thread from the thread pool.
    • Do not use threads for CPU-intensive tasks. It makes no sense if you have 4 CPUs and more than 4 CPU-intensive tasks at the same time.
    • The number of threads running at the same time. Thread switching is expensive.

Use the following counter to obtain information about a running thread:

Category: Thread

% Processor time: displays the processor time percentage used by each thread.

Context switches/sec: displays the context switching rate per second for each thread.

Stringbuilder

Refer to the use of stringbuilder in memory optimization.

Regular Expression Initialization

When a regular expression is used to match a string, there are two solutions. Solution 1: Use a regular expression to initialize the RegEx object, and then use the ismatch method of the object. Solution 2: directly call the static method RegEx. ismatch.

If you need to perform the same match multiple times, it is best to initialize the RegEx object outside the loop instead of using the ismatch static version.

If the website needs to match the regular expression many times, you can create a static class containing the regular expression object. In this way, Initialization is only performed when the program is started, rather than every request.

Utcnow

Datetime. utcnow is much faster than datetime. Now.

Foreach

C # statement foreach is a convenient way to traverse a set, but because enumerator is used, it is slower than the common for loop.

Virtual attributes

If the attribute in the definition class is virtual, the derived class is allowed to override this attribute. However, this will slow down attribute access because the compiler will no longer inline it.

Therefore, if you read the virtual attribute multiple times, you can copy the attribute to the local variable to improve the performance.

Avoid unnecessary handling
    • Early verification. Make sure that the data is correct before processing the data.
    • Check whether the user is online before performing expensive operations. Use response. isclientconnected to check.
    • Check page. ispostback so that data in viewstate is not regenerated.
Shorten the HTTP Pipeline

If you do not need some HTTP modules, you can remove them from web. config. For example:

 
<System. Web>  
More resources
    • 10 tips for writing High-Performance Web applications: http://msdn.microsoft.com/en-us/magazine/cc163854.aspx? Ppud = 4.
    • Improving ASP. NET performance: http://msdn.microsoft.com/en-us/library/ms998549.aspx.
    • base class library performance tips and tricks: http://msdn.microsoft.com/en-us/magazine/cc161090.aspx.

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.