Professional Documents
Culture Documents
Garbage Colleciton
Garbage Colleciton
NET'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.
.NET 垃圾回收器为应用程序管理内存的分配和释放。每创建一个新对象,CLR 会从托
管堆 (Managed Heap) 上为该对象分配内存。只要托管堆上的内存(地址)空间够用 ,
CLR 会继续为新创建的对象分配内存。然而,内存空间是有限的,最终,垃圾回收器
必须执行回收操作以清理出一些内存空间。基于内存分配模式,垃圾回收器的优化引
擎会决定执行内存回收的最佳时间。当它执行内存回收时,它会检查那些分配在托管
堆上并且在应用程中不再被使用的对象,并执行回收操作,以收回这些对象所占用的
内存。
分配在托管堆上的内存越少,垃圾回收所需要的做的工作就越少。当你为对象分配内
存时,不要使用超过你需要的值,比如当你仅需要 15 个字节时,却分配了一个 32 个
字节的数组。
当垃圾回收被触发时,垃圾回收器会回收那些生命周期已结束的对象所占用的内存空
间。回收过程中,垃圾回收器也会把继续存留的对象压到一起,并移出不再使用的空
间,因此,托管堆占用的空间就会变得比之前小一些。这确保分配的对象能够在托管
堆上连续在一起。
托管堆可以被认为是两个堆的总和:大对象堆与小对象堆。
大对象堆包括那些大于 85000 字节的对象,这些对象通常是数组,而实例对象少有非
常大的。
The garbage collector uses the following information to determine whether objects are live:
Stack roots. Stack variables provided by the just-in-time (JIT) compiler and stack
walker.
Garbage collection handles. Handles that point to managed objects and that can be
allocated by user code or by the common language runtime.
Static data. Static objects in application domains that could be referencing other
objects. Each application domain keeps track of its static objects.
Before a garbage collection starts, all managed threads are suspended except for the thread
that triggered the garbage collection.
The following illustration shows a thread that triggers a garbage collection and causes the
other threads to be suspended.