1. Avoid meaningless variable initialization actions
The CLR ensures that all objects are initialized before accessing them by zeroing out the allocated memory. Therefore, there is no need to reinitialize variables to 0, false, or null.
//Generally expert 10 or less items
private HashTable _items = null;
private NameValueCollection = _queryString = null;
private string _siteUrl = null;
private Uri _currentUri;
string rolesCacheKey = null;
string authenticationType = "forms";
bool _isUrlRewritten = false;
string _rawUrl = null;
HttpContext _httpContext = null
DateTime requestStarTime = DateTime.Now;
It should be noted that the local variables in the method are not allocated from the heap but from the stack, so C# will not clear them. If an unassigned local variable is used, an alarm will occur during compilation. Don't assign values to member variables of all classes just because of this impression. The mechanisms of the two are completely different!
2. ValueType and ReferenceType
(1). Pass value type parameters by reference.
Value types are allocated from the call stack and reference types are allocated from the managed heap. When a value type is used as a method parameter, parameter value copying is performed by default, which negates the efficiency advantage of value type allocation. As a basic technique, passing value type parameters by reference can improve performance.
private void UseDateByRef(ref DateTime dt){ }
public void foo()
{
DateTime now = DateTime.Now;
UseDateByRef(ref now);
}
(2), Provide Equals method for ValueType
The ValueType.Equals method implemented by .net by default uses reflection technology and relies on reflection to obtain the values of all member variables for comparison. This is extremely inefficient. If the Equals method of the value object we write is to be used (for example, placing the value object in a HashTable), then the Equals method should be overloaded.
public struct Rectangle
{
public double Length;
public double breadth;
public override bool Equals (object ob)
{
if (ob is Rectangle)
return Equels ((Rectangle)ob))
else
return false ;
}
private bool Equals (Rectangle rect)
{
return this .Length == rect.Length && this .Breadth == rect.Breach;
}
}
(3) Avoid packing and unboxing
C# can automatically convert between value types and reference types through boxing and unboxing. Boxing requires allocating objects from the heap and copying values, which has a certain performance cost. If this process occurs in a loop or is called frequently as an underlying method, you should be wary of the cumulative effect.
A common situation arises when working with collection types. For example:
ArrayList al = new ArrayList();
for ( int i = 0 ; i < 1000 ; i ++ )
{
al.Add(i); // Implicitly boxed because Add() takes an object
}
int f = ( int )al[ 0 ]; // The element is unboxed
The solution to this problem is to use the generic collection type supported by .net2.0.