Personal ASP. Net Program Performance Optimization experience series:
My experiences in ASP. NET program performance optimization (1): Database
My experiences in ASP. NET program performance optimization (1): Database (another article)
Personal experience in ASP. NET program performance optimization (2): ASP. NET code optimization
Personal experience in ASP. NET program performance optimization (3): frontend Performance Optimization
------------------------------------------------------------------------------
For ASP. net program performance, the importance is not by database, Asp.. Net code and the front end are sorted in this way. Different application environments may have different important influencing factors. Except for external hardware and network factors, users enter the address in the address bar, the entire web page is completely displayed in the user's browser. This time is equal to the sum of all factors. Generally, under normal circumstances, different roles are required to deal with these three factors: DBA is responsible for database optimization, and programmers optimize ASP. net code and front-end engineers optimize the front-end performance. If the division of labor is not so detailed, there will be a cross-division of labor. The worst case is that there is only one person who is a DBA, it is also a programmer who needs to write all the front-end parts. -- This may be a bad thing. You are in the hands of a stingy boss, and the boss treats you as a donkey. It will also be a good thing, web development itself is a task that requires a lot of knowledge, from which you will learn more, in this way, we will have a more comprehensive understanding of network programs (even so ............ Tat ).
I. Use server controls with caution
ASP. some server controls in. NET are extensions of HTML controls, including buttons, labels, literal, Textbox, dropdownlist, checkbox, radiobutton, and ASP.. Net encapsulates these controls and binds the delegate events of the controls, so that ASP. net programmers can drag controls like VB and winfornm to handle interface layout and events. HTML controls generated by these controls basically do not generate redundant code. If you are not very concerned about web standards, the impact will not be great. It is worth mentioning that the label generated is the <span> label. The label generated by checkbox (list) and radiobutton (list) is usually like this:
<SPAN class = "checkbox"> <input id = "chksel" type = "checkbox" name = "chksel"/> <label for = "chksel"> select </label> </span>
From the perspective of web standards, this code is to be scolded by front-end engineers, Which is meaningless and a waste of code.
Another type of server control is Microsoft's proud big data display control, including the gridview, datalist, detailsview, listview, repeater, and so on. This type of control is not recommended except the Repeater control, this kind of dumb control will make programmers more dumb, and more importantly, it will affect the code performance. Taking the gridview as an example, after the datasource is bound, all the data will be loaded on the server memory, programmers love its paging function. You can click it a few times. However, if there is a large amount of data, such as hundreds or thousands of pages, you can wait for the last restroom. The Repeater control is recommended because it does not generate any code and only displays the content of the data source repeatedly. We recommend that you use stored procedures + repeater for the most commonly used paging function. This is suitable for both performance and HTML code cleanliness.
HTML is the most basic capability of Web developers. If you cannot hand-write HTML, it is difficult to be competent for web development. The Code obtained by dragging controls using Visual Studio is very messy, we recommend that you write HTML in one row in the Open Source view, even if it is a server control.
Ii. viewstate Problems
Viewstate itself is a very good idea. Microsoft's innovation capability is recognized in the industry because users submit data to servers, such as names, ages, and gender, the server verifies the validity of the data. If the format is incorrect or the input is empty, the server returns some error messages to the user, however, the problem is that the content of the form submitted by the user is no longer available. If the content to be entered in the form is large, the user will go crazy. ASP. net is very kind to store the submitted content in this webpage. Even if the data submission fails to pass verification, the data remains in its original location, this method is very helpful to users and developers. By the way, it is often used with verification controls and looks very user-friendly, but it is the culprit of generating a large amount of bloated code.
Personal experience in ASP. NET program performance optimization (2): Asp.net code optimization
This messy code is the result of base64 encryption on existing data. It will make your browser feel slower when downloading your webpage.
In my opinion, if you want to set enableviewstate to false globally for Internet products (including website classes), you can set it in Web. config. The solution is to use JavaScript for verification. Now the Form Verification library is very convenient to use.
Iii. Problems in ADO. net
1. sqldatareader and dataset selection:
Sqldatareader is a class for fast forward data reading. It only performs data flow for data retrieved from the SQL server data source, dataset stores the database content in the memory of the server as a logical database. If the data volume is large, the performance of the server will be greatly affected. Therefore, we should make reasonable choices in actual projects.
2. Select executenonquery and executescalar:
Executescalar returns the first column of data in the first row after the execution result. executenonquery only returns the number of affected rows. In some cases, we only need to know whether the execution is successful, that is, whether the number of rows returned by executenonquery is greater than 0. Sometimes we want to know the data of the returned results. For example, after executing insert, we need to use scope_identity () to obtain the returned primary key ID. Select executenonquery and executescalar as needed.
Iv. Rational Use of Cache
The use of cache is a top priority. This can be explained as follows: when one hundred people need to fetch data from the server, the program will query and retrieve data from the SQL Server database each time, this will have a great impact on performance. This data can be temporarily cached on the server so that the data will be stored in the server's memory during the first query, other users will retrieve the data directly from the server during the cache time to avoid multiple requests to the data source, which will improve the program performance. Of course, if the cached data changes dynamically, you can set the cache time or clear the cache when updating the data, for example, in the article system.
Here I provide a cache class for my personal use:
Using system; using system. collections; using system. web; using system. web. caching; namespace cute. utility {// <summary> // @ cache processing // @ walkingp // @ http://www.cnblogs.com/walkingp // @ http://www.walkingp.com // @ walkingp@126.com // @ /// </Summary> public class cachehelper {private cache webcache = httpcontext. current. cache; private int defaultcachetime = 60; // <summary> // get A certain item // </Summary> /// <Param name = "key"> </param> /// <returns> </returns> Public object get (string key) {return this. webcache. get (key );} /// <summary> /// determine whether a certain item exists /// </Summary> /// <Param name = "key"> </param> // <returns> </returns> Public bool exists (string key) {return this. webcache. get (key )! = NULL ;} /// <summary> /// add an item to the cache /// </Summary> /// <Param name = "key"> </param> /// <Param name = "value"> </param> // <returns> </returns> Public bool add (string key, object value) {return this. add (Key, value, defaultcachetime );} /// <summary> /// add an item to the cache and set the cache time to minute minutes /// </Summary> /// <Param name = "key"> </param> /// <Param name = "value"> </param> // <Param name = "Minute"> minutes to be cached </param> /// <r Eturns> </returns> Public bool add (string key, object value, int minute) {return this. add (Key, value, timespan. fromminutes (minute);} // <summary> // Add an item to the cache, and set the cache time of an item. /// </Summary> /// <Param name = "key"> </param> /// <Param name = "value"> </param> /// <Param name = "span"> time slice to be cached </param> /// <returns> </returns> Public bool add (string key, object value, timespan span) {This. webcache. insert (key, Value, null, datetime. now. add (SPAN), system. web. caching. cache. noslidingexpiration); Return true ;}/// <summary> /// add an item to the cache, and set the cache time to expire /// </Summary> /// <Param name = "key"> </param> /// <Param name = "value"> </param> /// <Param name = "expiretime"> cache expiration time </param> /// <returns> </returns> Public bool add (string key, object value, datetime expiretime) {This. webcache. insert (Key, value, null, expiretime, System. web. caching. cache. noslidingexpiration); Return true ;} /// <summary> /// remove an item from the cache /// </Summary> /// <Param name = "key"> </param> // /<returns> </returns> Public bool remove (string key) {return this. webcache. remove (key )! = NULL;} // <summary> /// remove all caches /// </Summary> Public void removeall () {system. web. caching. cache _ cache = httpruntime. cache; idictionaryenumerator cacheenum = _ cache. getenumerator (); arraylist Al = new arraylist (); While (cacheenum. movenext () {Al. add (cacheenum. key);} foreach (string key in Al) {_ cache. remove (key );}}}}
5. Other Optimizations
1. Avoid unpacking:
We know the value type and reference type in C #. C # basic data type, struct, and enum belong to the value type. The reference types include class, array, interface, delegate, andString)Yes, the string also belongs to the reference type. The value type is stored in the memory as a stack, and the reference type is heap) (This concept is a pointer to the C language ). To convert a value type to a reference type, it is called packing, and vice versa. As follows:
Int I = 0; syste. Object OBJ = I; // binning Int J = (INT) OBJ; // unpack
Packing and unpacking will affect program performance, so we should avoid it as much as possible in the program. Therefore, the program write will improve the performance a little bit:
String info="My Age is" + 24.ToString();
2. Use stringbuilder
If too many strings are concatenated, the program performance may be affected, because each time ++ creates a new string, that is, it opens up a space in the memory for this new string. Using stringbuilder can reduce this consumption. We recommend that you use it when there are too many connection strings.
I also remember that the stringbuiler problem was once quarrelled in the blog Park. If you have any questions, please let us know.
3. Avoid unnecessary tolower () and toupper ()
Similarly, a new String object is created. You can use the compare method to compare strings if you do not need to reduce the number of strings.
4. Avoid unnecessary exception capture
Maybe your consideration of things is too complicated, and you are too sensitive to exception capture, so try... catch is a little more useful, so it is recommended that it be used only when it is used, not when it is not used.
5. Use stored procedures
Frequent SQL statements are transferred back and forth to the database server on the Web server, which affects the program execution efficiency, A more effective method is to encapsulate SQL statements that are complex and frequently used as stored procedures for calling.
Summary
The above is my personal summary of ASP. net code optimization methods and experiences, at this level of optimization needs more to C # language, ADO. net mechanism and ASP. net operating mechanism more and more in-depth. There is no end to optimization. You are welcome to improve and supplement it.
Recommended books
The book provides the most in-depth explanation of C.
ASP. NET: a book written by a friend in the garden. I borrowed it from Dudu last time (I often see Dudu, envy ?), Who said there are no good it books in China?
C # graphic Tutorial: Foreigners also play with the title party and almost ruined a good book. for students who feel familiar with C #, they must buy this book and read it carefully, there will be a feeling of "so simple.
-------------------------------------------------------
This article is also posted on my personal homepage: http://www.walkingp.com/