【IT168技术文档】我们在实际编程中使用的内存往往都会超出程序需要的内存,对于桌面应用程序内存是相对廉价的,但如果你在开发ASP.NET应用程序,需要处理服务器上大量的内存时,过度使用内存可能会带来很多痛苦,因此有必要讨论一下.NET内存管理的非常好的实践,以减少内存浪费。
程序员在为类中的成员变量获取内存时往往有些多余的行为,因为有些不必要的内存使用会浪费掉一些内存空间,我们来看一段代码:
public class BadUse
{
private SqlConnection con = new SqlConnection();
private DataSet ds = new DataSet("MyData");
public BadUse() {}
public BadUse(string connectionString)
{
SqlConnection = new SqlConnection(connectionString);
}
public BadUse(SqlConnection con)
{
this.con = con;
}
}
如果在我们的系统中使用了多余的内存,类在被调用之前,甚至是构造函数被调用之前,就调用了对象成员初始化程序,它将为所有成员变量获取内存,在上面的代码中,在初始化期间我们创建了一个SqlConnection对象,在那之后,我们都调用默认的构造函数或创建对象的构造函数,因此没有使用已经创建好的对象,重新创建了一遍对象,因此浪费了内存空间。
.NET内存管理非常好的实践方法:
{
private SqlConnection con = null;
private DataSet ds = null;
public SqlConnection Connection // Better to use Properties
{
get
{
if(this.con == null) // Always check whether there is an existing object assigned to member
this.con = new SqlConnection();
return this.con;
}
set
{
if(value == null || this.con !=null)
{
this.con.dispose(); // Clears out Existing object if member is assigned to Null
this.con = null; // Always better to assign null to member variables
}
if(value !=null) this.con = value;
}
}
public GoodUse() {}
public GoodUse(string connectionString)
{
this.Connection = new SqlConnection(connectionString); //Assignes new object to null member
}
public GoodUse(SqlConnection con)
{
this.con = con;
}
}