Seven aspects of ASP.net program performance optimization (C # (or vb.net) program Improvement) _ Practical skills

Source: Internet
Author: User
Tags add numbers error handling sql injection
1, use the value type of ToString method
When connecting strings, you often add numbers directly to the string using the "+" number. Although this method is simple, it can get the correct result, but because it involves different data types, the number needs to be converted into a reference type by boxing operation to be added to the string. However, boxing operations have a greater impact on performance because, when such processing is done, a new object is allocated in the managed heap, and the original value is copied to the newly created object.
Use the ToString method of value types to avoid boxing operations, thereby improving application performance.
int num=1;
String str= "Go" +num. ToString ();
2, the use of StringBuilder class
The string class object is immutable, and the method ToString does not significantly improve performance for a string object that is essentially recreating a string object and assigning the new value to the object.
When working with strings, it is best to use the StringBuilder class, whose. NET namespace is system.text. Instead of creating a new object, the class operates directly on the string through methods such as Append,remove,insert, and returns the result of the operation through the ToString method.
Its definition and operation statements are as follows:
int num;
System.Text.StringBuilder str = new System.Text.StringBuilder (); Creating a String
Str. Append (Num. ToString ()); Add Numeric num
Response.Write (str. ToString); Show action Results
3. Redirect between pages of the same application using the HttpServerUtility.Transfer method
Using the Server.Transfer syntax, this method can be used in a page to avoid unnecessary client redirection (Response.Redirect).
4, avoid the use of ArrayList.
Because any object added to the ArrayList must be sealed to the System.Object type, remove the data from the ArrayList, to remove the actual type back. It is recommended that you use a custom collection type instead of ArrayList. ASP.net 2.0 provides a new type, called Generics, which is a strong type, using generic collections to avoid the occurrence of enclosures and unboxing and improve performance.
5. Use Hashtale instead of other dictionary collection types
(such as stringdictionary,namevaluecollection,hybridcollection), you can use Hashtable when storing small amounts of data.
6. Declare a constant for the string container, and do not encapsulate the character directly in the double quote "".
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 (), ToLower () conversion string for comparison, instead of string.compare, it can ignore case comparisons.
Cases:
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 empty. (Note the length of the input data to prevent SQL injection attacks)
Comparing the length property of a string object with 0 is the quickest way to avoid unnecessary calls to ToUpper or ToLower methods.
8, type conversion int32.tryparse () is better than Int32.Parse () than Convert.ToInt32 ().
Suggestions. NET1.1 with Int32.Parse (); NET2.0 with Int32.TryParse ().
Because:
Convert.ToInt32 will be the final analytical work agent to int32.parse;
Int32.Parse will be the final analytical work agent to number.parseint32;
Int32.TryParse will give the final analytical work to Number.tryparseint32.
9, if only from the XML object reading data, with read-only XPathDocument instead of XmlDocument, you can raise High-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. To avoid declaring variables in the circulation body, you should declare variables outside of the loop body and initialize them in the loop body.
One of the basic principles to be followed in C # 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 the generic 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, in the use of try...catch...finally, to release the resources used in the finally, such as connection, file flow, etc.
Otherwise, the resource occupied after the catch to the error cannot be freed.
Try
{}
Catch
{}
Finally
{
Conntion.close ();
}
13, do not use exception control program flow
Some programmers may use exceptions to implement some process control. For example:
try{
Result=100/num;
}
Catch (Exception e)
{
result=0;
}
But in fact, exception is very consuming system performance. Unless necessary, exception control should not be used to implement program flow. The above code should be written as:
if (num!=0)
Result=100/num;
Else
result=0;
14, to avoid the use of recursive calls and nested loops, using them will seriously affect performance, when it is necessary to use.
15. Disabling vb.net and JScript Dynamic Data types
Variable data types should always be shown, which saves the execution time of the program. In the past, one of the reasons developers liked to use Visual Basic, VBScript, and JScript was their so-called "no type" nature. Variables do not require an explicit type declaration and can be created simply by using them. When an assignment is made from one type to another, the conversion is performed automatically. However, this convenience can greatly impair the performance of the application.
Such as:
For best performance, assign a type to a JScript. NET variable when it is declared. 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.