asp.net Performance Optimization Skills Summary _ Practical skills

Source: Internet
Author: User

This paper collects and summarizes various techniques of asp.net performance optimization, which has good reference value for ASP.net developers. The specific contents are as follows:

Choosing a session-state storage method

In webconfig file configuration:

<sessionstate mode= "???" Stateconnectionstring= "tcpip=127.0.0.1:42424" 
 sqlconnectionstring= "Data source= 127.0.0.1; Trusted_connection=yes " 
cookieless=" false "timeout="/> 

ASP.net has three ways of storing session-state information:

1. Stored in Process: property mode = InProc
Features: Best performance, fastest speed, but not shared across multiple servers.

2. Stored in State server: property mode = "StateServer"
Features: Use this method when you need to maintain user session information across servers.
But the information is stored on the state server, and once the state server fails, the information is lost

3. Stored in SQL Server: properties mode= "SQL Server"
feature: The workload will become larger, but the information will not be lost.

Add one point:
I. Because some pages do not require session state, you can disable session state:
As shown in the following code:

<%@ Page enablesessionstate= "false"%>

Ii. If the page requires access to session variables but does not allow them to be modified, you can set the page session state to read-only:
As shown in the following code:

<%@ Page enablesessionstate= "false"%>

When used, you can choose a certain way depending on the circumstances.

Ii. Use of Page.IsPostBack

Page.IsPostBack Indicates whether it was returned from the client. When it is first run, it is not returned from the client, its value is false, when the event on the page is triggered or when the page is refreshed, the value of Page.IsPostBack becomes true because it is postback;

Generally in: Page_Load method uses:

private void Page_Load (Object Sender,eventargs e)
{
if (! Page.IsPostBack)
{
   ...;///Initialize the code for the page. The code executes the first time the page is initialized, and when the second postback is made,
   //no longer executes. Improve efficiency. 
}
}

There are often times when you have to use IsPostBack, because some controls are initialized to maintain their state.
For example: DropDownList, if you initialize each time, the user will be initialized to the default value regardless of their options.

Third, avoid using server controls

1. General static display information, try not to use server-side control display. Because the server-side control needs to be sent back to the server for execution, it can reduce the execution efficiency of the program, generally using <DIV> display. If you use a server-side control, you can increase the efficiency by removing the runat= "server".

2. Disables the status view of the server-side controls, some controls do not need to maintain their state, and can set their properties: Enableviewstate=false;
If the entire page control does not need to maintain a status view, you can set the status of the entire page to false:
As shown in the following code:

<%@ Page enableviewstate= "false"%>

3. Configure in the Web.config file:
asp.net sessionss can be configured in sessionsstate elements in Web.config or machine.config.
The following are examples of settings in Web.config:

<sessionsstate timeout= "Ten" cookieless= "false" mode= "Inproc"/> 

Iv. avoiding the use of the DataGrid

We all know that the DataGrid is powerful. But while powerful, it increases performance overhead. General use of other controls: DataList
or repeater control can be implemented, try not to use a DataGrid.

Five, String operations

1. avoid boxing operation. The operation efficiency of boxing operations is comparatively low .
For example, run two code snippets:

String test= "";
for (for int i=0;i<10000;i++)
{ 
  test = test + i;       
}

And

String test= "";
for (for int i=0;i<10000;i++)
{ 
  test = test + i.tostring ();       
}

The following code snippet is obviously efficient. Since I is integral, the system first converts the I boxing into a string type and then connects. It takes time.
The reader can copy the test on his machine.

2. Using the Stringbulider class

When string concatenation is made: string str = str1 + str2 + ...;
There are generally more than three connections, preferably with StringBuilder instead of the string class. StringBuilder can avoid recreating a string object caused by
Loss of performance.
typically used to assemble SQL statements: Stringbulider. Readers can test them on their own machines.

3. Try to use less:

Try
{}
catch
{}
finally
{}

Statement. This statement performs less efficiently.

Six, ADO. NET use aspect optimization

1. The database connection is turned on and off. Open when you need to connect, and close the connection immediately after you have accessed the database.
For example, or look at two code snippets:

Code 1:

DataSet ds = new DataSet ();
  SqlConnection myconnection = new SqlConnection ("Server=localhost; Uid=sa; pwd=; Database=northwind ");
  SqlCommand mycommand = new SqlCommand (strsql,myconnection);  
  SqlDataAdapter Myadapter=new SqlDataAdapter (QUERYSTR,CONNECTIONSTR);
Myconnection.open ();   Open
 the connection for (int i=0;i<1000;i++)  //for loop to simulate business logic operations before obtaining data
 {
  thread.sleep (1000);
}
Myadapter.fill (DS);
for (int i=0;i<1000;i++)  //for loops simulate business logic operations after obtaining data
{
  thread.sleep (1000);
}
Myconnection.close ();   Close connection

Code 2:

 DataSet ds = new DataSet ();
  SqlConnection myconnection = new SqlConnection ("Server=localhost; Uid=sa; pwd=; Database=northwind ");
  SqlCommand mycommand = new SqlCommand (strsql,myconnection);  
  SqlDataAdapter Myadapter=new SqlDataAdapter (QUERYSTR,CONNECTIONSTR);    
 for (int i=0;i<1000;i++)  //for Loop simulates the business logic operation before obtaining data
 {
  thread.sleep (1000);
}
Myconnection.open ();   Open Connection
  Myadapter.fill (DS);
 Myconnection.close ();   Closes
the connection for (int i=0;i<1000;i++)  ////for loop to simulate business logic operations after obtaining data
{
  thread.sleep (1000);
}

Show II code better than I code, I early in the connection does not put, if the user a lot of words, easy to connect pool full situation. There is a panic phenomenon when serious.

2. Database query

I. Generate SQL statements directly. SQL Server compiles it every time, and there is no significant performance improvement. It's also not safe enough. Easy to be attacked.
Ii. use SQL commands with parameters. This way SQL Server compiles only once, and the compiled commands can be reused for different parameters. Improved performance.
III. use SQL Server stored procedures. Compile one time.  Independent, easy to modify and maintain.  A function that can be used to send multiple statements at once. Reduce network traffic. It is not necessarily that stored procedures are more efficient than statements, and if business logic is complex, sometimes statements are more efficient than stored procedures.

Seven, cache optimization

Caching is divided into two types: page caching and API caching.

1. Use page caching and fragment caching:

<%@ OutputCache duration= "5" varybyparam= "None"%> <%@ OutputCache duration=60 varybyparam= 
"TextBox1, TextBox2 "%>

Description: Duration is to set the cache expiration time;
Varbyparam is whether the setting varies according to the parameters, none is all parameters using the same cache,
When the TextBox1 is set, it is cached separately according to the different values of the TextBox1, and when there are multiple parameters, the cache is combined ;

2.API Cache. For use in applications

I. Example of a cache use:
Http://www.jb51.net/article/52399.htm

Ii. attention to Page.cache and HttpContext.Current.Cache differences when used:

They refer to the same object, in page, with Page.cache, if used in Global.asax or in their own class: HttpContext.Current.Cache
In some cases, because it is not HttpContext, use Httpruntime.cache.

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.