分类目录归档:后端

asp.net性能优化的几个方面

c#(或vb.net)程序改进
1、使用值类型的ToString方法
在连接字符串时,经常使用"+"号直接将数字添加到字符串中。这种方法虽然简单,也可以得到正确结果,但是由于涉及到不同的数据类型,数字需要通过装 箱操作转化为引用类型才可以添加到字符串中。但是装箱操作对性能影响较大,因为在进行这类处理时,将在托管堆中分配一个新的对象,原有的值复制到新创建的 对象中。
使用值类型的ToString方法可以避免装箱操作,从而提高应用程序性能。
int num=1;
string str="go"+num.ToString();

2、运用StringBuilder类
String类对象是不可改变的,对于String对象的重新赋值在本质上是重新创建了一个String对象并将新值赋予该对象,其方法ToString对性能的提高并非很显著。
在处理字符串时,最好使用StringBuilder类,其.NET 命名空间是System.Text。该类并非创建新的对象,而是通过Append,Remove,Insert等方法直接对字符串进行操作,通过ToString方法返回操作结果。
其定义及操作语句如下所示:
int num;
System.Text.StringBuilder str = new System.Text.StringBuilder(); //创建字符串
str.Append(num.ToString()); //添加数值num
Response.Write(str.ToString); //显示操作结果

3、使用 HttpServerUtility.Transfer 方法在同一应用程序的页面间重定向
采用 Server.Transfer 语法,在页面中使用该方法可避免不必要的客户端重定向(Response.Redirect)。
4、避免使用ArrayList。
因为任何对象添加到ArrayList都要封箱为System.Object类型,从ArrayList取出数据时,要拆箱回实际的类型。建议使用自定义 的集合类型代替ArrayList。asp.net 2.0提供了一个新的类型,叫泛型,这是一个强类型,使用泛型集合就可以避免了封箱和拆箱的发生,提高了性能。
5、使用HashTale代替其他字典集合类型
(如StringDictionary,NameValueCollection,HybridCollection),存放少量数据的时候可以使用HashTable.
6、为字符串容器声明常量,不要直接把字符封装在双引号" "里面。
//避免
MyObject obj = new MyObject();
obj.Status = "ACTIVE";
//推荐
const string C_STATUS = "ACTIVE";
MyObject obj = new MyObject();
obj.Status = C_STATUS;
7、不要用ToUpper(),ToLower()转换字符串进行比较,用String.Compare代替,它可以忽略大小写进行比较.
例:
const string C_VALUE = "COMPARE";
if (String.Compare(sVariable, C_VALUE, true) == 0)
{
Console.Write( "相同");
}
也可以用str == String.Empty或者str.Length == 0判断是否为空。(注意判断输入数据的长度,可防止sql注入式攻击)
将String对象的Length属性与0比较是最快的方法,避免不必要的调用 ToUpper 或 ToLower 方法。
8、类型转化Int32.TryParse()优于Int32.Parse()优于Convert.ToInt32()。
建议.NET1.1下用Int32.Parse();.NET2.0用Int32.TryParse()。
因为:
Convert.ToInt32 会把最终的解析工作代理给 Int32.Parse;
Int32.Parse 会把最终的解析工作代理给Number.ParseInt32;
Int32.TryParse 会把最终的解析工作代理给Number.TryParseInt32。
9、如果只是从XML对象读取数据,用只读的XPathDocument代替XMLDocument,可以提高性能
//避免
XmlDocument xmld = new XmlDocument();
xmld.LoadXml(sXML);
txtName.Text = xmld.SelectSingleNode( "/packet/child").InnerText;
//推荐
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、避免在循环体里声明变量,应该在循环体外声明变量,在循环体里初始化。

C#程序开发要遵循的一个基本原则就是避免不必要的对象创建

//避免
for(int i=0; i <10; i++)
{
SomeClass objSC = new SomeClass();
}
//推荐
SomeClass objSC = null;
for(int i=0; i <10; i++)
{
objSC = new SomeClass();
}
11、捕获指定的异常,不要使用通用的System.Exception.
//避免
try
{
<some logic>
}
catch(Exception exc)
{
<Error handling>
}

//推荐
try
{
<some logic>
}
catch(System.NullReferenceException exc)
{
<Error handling>
}
catch(System.ArgumentOutOfRangeException exc)
{
<Error handling>
}
catch(System.InvalidCastException exc)
{
<Error handling>
}
12、使用Try…catch…finally时, 要在finally里释放占用的资源如连接,文件流等
不然在Catch到错误后占用的资源不能释放。

try
{}
catch
{}
finally
{
conntion.close();
}

13、不要用Exception控制程序流程
有些程序员可能会使用异常来实现一些流程控制。例如:
try{
result=100/num;
}
Catch(Exception e)
{
result=0;
}
但实际上,Exception是非常消耗系统性能的。除非必要,不应当使用异常控制来实现程序流程。上面的代码应当写为:
if(num!=0)
result=100/num;
else
result=0;

14、避免使用递归调用和嵌套循环,使用他们会严重影响性能,在不得不用的时候才使用。
15、禁用VB.net和Jscript动态数据类型
应当始终显示地申明变量数据类型,这能够节约程序的执行时间。以往,开发人员喜欢使用 Visual Basic、VBScript 和 JScript 的原因之一就是它们所谓“无类型”的性质。变量不需要显式类型声明,并能够简单地通过使用来创建它们。当从一个类型到另一个类型进行分配时,转换将自动执 行。不过,这种便利会大大损害应用程序的性能。
如:
为了获得最佳的性能,当声明 JScript .NET 变量时,请为其分配一个类型。例如,var A : String;

C#中class和struct的区别和用法

1,class 是引用类型,structs是值类型

既然class是引用类型,class可以设为null。但是我们不能将struct设为null,因为它是值类型。

struct AStruct
{
  int aField;
}
class  AClass
{
  int aField;
}
class MainClass
{
  public static void Main()
  {
    AClass b = null; // No error.
    AStruct s = null; // Error [ Cannot convert null to 'AStruct'
    because it is a value type ].
  }
}

2,当你实例一个class,它将创建在堆上。而你实例一个struct,它将创建在栈上

3,你使用的是一个对class实例的引用。而你使用的不是对一个struct的引用。(而是直接使用它们)

4,当我们将class作为参数传给一个方法,我们传递的是一个引用。struct传递的是值而非引用。

5,structs, 不可以有初始化器,class可以有初始化器。

class MyClass
{
  int myVar =10;  //  no syntax error.
  public void MyFun( )
  {
    // statements
  }
}
struct MyStruct
{
  int myVar = 10;  //  syntax error.
  public void MyFun( )
  {
    // statements
  }
}

6,Classes 可以有明显的无参数构造器,但是Struct不可以

class MyClass
{
  int myVar = 10;
  public MyClass( ) // no syntax error.
  {
    // statements
  }
}
struct MyStruct
{
  int myVar;
  public MyStruct( ) // syntax error.
  {
    // statements
  }
}

7, 类使用前必须new关键字实例化,Struct不需要

MyClass aClassObj;     //  MyClass aClassObj=new MyClass(); is the correct format.aClassObj.
myVar=100;//NullReferenceException(because aClassObj does not contain a reference to an object of type myClass).
MyStruct  aStructObj;
aStructObj.myVar=100; //  no exception.

8, class支持继承和多态,Struct不支持. 注意:但是Struct 可以鹤类一样实现接口

9, 既然Struct不支持继承,其成员不能以protected 或Protected Internal 修饰

10, Class的构造器不需要初始化全部字段,Struct的构造器必须初始化所有字段

class MyClass    //No error( No matter whether the Field ’ MyClass.myString ’ is initialized or not ).
{
  int myInt;
  string myString;
  public MyClass( int aInt )
  {
    myInt = aInt;
  }
}
struct MyStruct    // Error ( Field ’ MyStruct.myString ’ must be fully assigned before it leaves the constructor ).
{
  int myInt;
  string myString;
  public MyStruct( int aInt )
  {
    myInt = aInt;
  }
}

11, Class可以定义析构器但是Struct不可以

12, Class比较适合大的和复杂的数据,Struct适用于作为经常使用的一些数据组合成的新类型。

适用场合:Struct有性能优势,Class有面向对象的扩展优势。
用于底层数据存储的类型设计为Struct类型,将用于定义应用程序行为的类型设计为Class。如果对类型将来的应用情况不能确定,应该使用Class。

C# 合并两个 list

using System;
using System.Collections.Generic;
class Program
{
  static void Main()
  {
    List a = new List();
    a.Add(1);
    a.Add(2);
    a.Add(5);
    a.Add(6);
    // Contains:
    // 1
    // 2
    // 5
    // 6
    int[] b = new int[3];
    b[0] = 7;
    b[1] = 6;
    b[2] = 7;
    a.AddRange(b);
    // Contains:
    // 1
    // 2
    // 5
    // 6
    // 7 [added]
    // 6 [added]
    // 7 [added]
    foreach (int i in a)
    {
      Console.WriteLine(i);
    }
  }
}
=== Output of the program ===
1
2
5
6
7
6
7

C# List 排序

写一个sorter

public class CourseSorter:IComparer
{
  #region IComparer Members
  public int Compare(CourseDto x, CourseDto y)
  {
    return x.Title.CompareTo(y.Title);
  }
  #endregion
}

用的时候list.sort(new Sorter());即可