Assu开发者_Python百科me I have a variable, which is a List(Of T)
, with 100 elements that are instances of a class....
If I set this variable to a new List(Of T)
with another 100 instances, the old ones totally disappear, right? They...die. Absolutely thing of the past, right?
Assuming nothing else points to those 100 things, then yes, they are eligible for garbage collection.
Unless the objects in the list are refered to/referenced by anything else, they will be put up for Garbage Collection
The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.
Yes, you declare a new place in memory for the variable, the old reference is lost and cleaned up at some time by garbage collection.
As others have stated, garbage collection should kick in. However, since you cannot control when that occurs, it's possible the data is still in memory. The most determined may find it.
If you are absolutely concerned about memory snooping, just use a loop to set the value of each element to something like 0, or a random value.
Not necessarily. The CLR (which is the runtime within which C# and VB.net code is executed) is a garbage collected system. Periodically, the runtime will examine the objects in memory, determine which ones aren't reachable from the "root set" (which includes local variables on the stack, for example), and free them.
In your example, if there are no other variables or fields holding a reference to your list (that are also reachable from the root set), then the original List will be freed. Additionally, if the List is freed, and if there are no remaining instances to each of the elements of the list, then those elements will also be freed. However, a reference to a single element of the list will not prevent the list itself or any other element of the list from being freed.
精彩评论