Should classed that use huge amounts of memory impmlement System.IDisposable
Suppose I have created a class that causes objects to use huge amounts of memory, but no unmanaged resources:
class TestMemory
{
public int[] intarray = new int[1000000];
}
Normally if I create an object of this class, and discard all references to the object after use, the garbage collector will eventually take care of freeing the memory.
The problem is that it is uncertain when the garbage collector will do this. It will probably take seconds, maybe even minutes before the garbage collector will free the memory
Suppose I want to recreate this object often, for example like this (I know, mot efficient):
for (int i=0; i < 1E10; ++i)
{
List<TestMemory> myList = new List<TestMemory>();
for (int j=0; j < 400; ++j)
{
myList.Add(new TestMemory());
}
}
Should I worry that I run out of memory, or will the garbage collector do an extra Collect when more memory than currently available is requested? Is it wise to implement IDisposable for this managed code?
NO
IDisposable is for classes which own unmanaged resources (file handles, SQL transactions, allocations from native libraries).
If one thinks of memory as being a collection of warehouses of various sizes, a .NET GC cycle is somewhat equivalent to finding all the objects to which references exist, moving all such objects that are in one particular warehouse to a different warehouse, dynamiting the warehouse from which the objects were moved, and building a new empty warehouse on the site of the old one. In general, when a small warehouse gets full, objects that were found in them will get moved to a bigger one until that too gets full (whereupon the objects there will get moved to an even bigger one).
An important thing to note is that even if the system had some way of knowing that no reference existed to some particular object in one of the warehouses, that information wouldn't be very helpful, since the system generally doesn't care about things which are in the warehouses but to which no reference exists. Allocating warehouse space sequentially is much faster and easier than trying to allocate little bits and pieces here and there, and dynamiting and rebuilding the warehouse is likewise quick and easy.
There are a few situations in which code which uses a large array of a class type might benefit from nulling out all of the references within the array before abandoning the last reference to the array itself (especially if the array itself is very old, but contains references to mostly new objects). In general, though, one should figure that the system will perform GC cycles when it needs to reclaim memory, and won't benefit from the knowledge that pieces of memory could be reclaimed sooner.
链接地址: http://www.djcxy.com/p/54508.html