Seven aspects of asp.net program performance optimization (c # (or vb.net)

Source: Internet
Author: User
Tags add numbers

1. Use the ToString method of Value Type
When connecting strings, you often use the "+" sign to directly add numbers to strings. This method is simple and can get the correct results. However, because different data types are involved, the numbers must be converted to the reference type through the boxing operation before they can be added to the string. However, the packing operation has a great impact on the performance, because during such processing, a new object will be allocated in the managed heap, and the original value will be copied to the newly created object.
The Value Type ToString method can be used to avoid packing and improve application performance.
Int num = 1;
String str = "go" + num. ToString ();
2. Use the StringBuilder class
The String class object cannot be changed. In essence, the re-assignment of the String object re-creates a String object and assigns the new value to the object, the ToString method does not significantly improve the performance.
When processing strings, it is best to use the StringBuilder class. Its. NET namespace is System. Text. This class does not create a new object, but directly performs operations on strings through Append, Remove, Insert, and other methods, and returns the operation results through the ToString method.
Its definition and operation statement are as follows:
Int num;
System. Text. StringBuilder str = new System. Text. StringBuilder (); // create a string
Str. Append (num. ToString (); // Add the numeric value num
Response. Write (str. ToString); // display the operation result
3. Use HttpServerUtility. Transfer to redirect between pages of the same application
Use the Server. Transfer syntax to avoid unnecessary client redirection (Response. Redirect) by using this method on the page ).
4. 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. Asp.net 2.0 provides a new type called generic, which is a strong type. Using a generic set can avoid the occurrence of binning and unpacking and improve the performance.
5. Use HashTale to replace other dictionary set types
(Such as StringDictionary, NameValueCollection, and HybridCollection). HashTable can be used to store a small amount of data.
6. 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;
7. Do not use ToUpper () or ToLower () to convert strings for comparison., Replaced by String. Compare, which can be case-insensitive for comparison.
Example:
Const string C_VALUE = "COMPARE ";
If (String. Compare (sVariable, C_VALUE, true) = 0)
{
Console. Write ("same ");
}
You can also use str = String. Empty or str. Length = 0 to determine whether it is null. (Check the length of the input data to prevent SQL injection attacks)
Comparing the Length attribute of a String object with 0 is the fastest way to avoid unnecessary calls to the ToUpper or ToLower method.
8. type conversion Int32.TryParse () is superior to Int32.Parse () and Convert. ToInt32 ().
We recommend that you use Int32.Parse () in. NET1.1 and Int32.TryParse () in. NET2.0 ().
Because:
Convert. ToInt32 will delegate the final parsing work to Int32.Parse;
Int32.Parse will delegate the final parsing work to Number. ParseInt32;
Int32.TryParse will delegate the final parsing work to Number. TryParseInt32.
9. If you only want to read data from an XML object, replacing XMLDocument with a read-only XPathDocument can improve the performance.
// Avoid
XmlDocument xmld = new XmlDocument ();
Xmld. LoadXml (sXML );
TxtName. Text = xmld. SelectSingleNode ("/packet/child"). InnerText;
// Recommended
XPathDocument xmldContext = new XPathDocument (new StringReader (oContext. Value ));
XPathNavigator xnav = xmldContext. CreateNavigator ();
XPathNodeIterator xpNodeIter = xnav. Select ("packet/child ");
ICount = xpNodeIter. Count;
XpNodeIter = xnav. SelectDescendants (XPathNodeType. Element, false );
While (xpNodeIter. MoveNext ())
{
SCurrValues + = xpNodeIter. Current. Value + ",";
}
10. Avoid declaring variables in the cyclic body. Declare variables in the circulating body and initialize them in the cyclic body.
C # A basic principle for program development is to avoid unnecessary object creation.
// Avoid
For (int I = 0; I <10; I ++)
{
SomeClass objSC = new SomeClass ();
}
// Recommended
SomeClass objSC = null;
For (int I = 0; I <10; I ++)
{
ObjSC = new SomeClass ();
}
11. Catch the specified Exception. Do not use general System. Exception.
// Avoid
Try
{
<Some logic>
}
Catch (Exception exc)
{
<Error handling>
}
// Recommended
Try
{
<Some logic>
}
Catch (System. NullReferenceException exc)
{
<Error handling>
}
Catch (System. ArgumentOutOfRangeException exc)
{
<Error handling>
}
Catch (System. InvalidCastException exc)
{
<Error handling>
}
12. When using Try... catch... finally, you must release the resources occupied in finally, such as connections and file streams.
Otherwise, the resources occupied after an error is caught cannot be released.
Try
{}
Catch
{}
Finally
{
Conntion. close ();
}
13. Do not use Exception to control program processes
Some programmers may use exceptions to implement some process control. For example:
Try {
Result = 100/num;
}
Catch (Exception e)
{
Result = 0;
}
However, exceptions consume a lot of system performance. Unless necessary, exception control should not be used to implement the program process. The above code should be written as follows:
If (num! = 0)
Result = 100/num;
Else
Result = 0;
14. Avoid using recursive calls and nested loops. Using them will seriously affect performance and will be used only when you have to use them.
15. Disable the Dynamic Data Types of VB.net and Jscript.
The variable data type should always be explicitly stated, which can save the execution time of the program. In the past, one of the reasons why developers like to use Visual Basic, VBScript, and JScript was their so-called "non-typed" nature. Variables do not need explicit type declarations and can be created simply by using them. When the data is allocated from one type to another, the conversion is automatically executed. However, this convenience will greatly damage the performance of the application.
For example:
To achieve optimal performance, assign a type to the JScript. NET variable when declaring it. For example, var A: String;

Related Article

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.