Free mag vol1 | Page 538

CHAPTER 13  UNDERSTANDING OBJECT LIFETIME Figure 13-4. A clean and compacted heap  Note Strictly speaking, the garbage collector makes use of two distinct heaps, one of which is specifically used to store very large objects. This heap is less frequently consulted during the collection cycle, given possible performance penalties involved with relocating large objects. Regardless, it is safe to consider the managed heap as a single region of memory. Understanding Object Generations When the CLR is attempting to locate unreachable objects, is does not literally examine each and every object placed on the managed heap. Doing so, obviously, would involve considerable time, especially in larger (i.e., real-world) applications. To help optimize the process, each object on the heap is assigned to a specific “generation.” The idea behind generations is simple: the longer an object has existed on the heap, the more likely it is to stay there. For example, the class that defined the main window of a desktop application will be in memory until the program terminates. Conversely, objects that have only recently been placed on the heap (such as an object allocated within a method scope) are likely to be unreachable rather quickly. Given these assumptions, each object on the heap belongs to one of the following generations: • Generation 0: Identifies a newly allocated object that has never been marked for collection. • Generation 1: Identifies an object that has survived a garbage collection (i.e., it was marked for collection but was not removed due to the fact that the sufficient heap space was acquired). • Generation 2: Identifies an object that has survived more than one sweep of the garbage collector.  Note Generations 0 and 1 are termed ephemeral generations. As explained in the next section, you will see that the garbage collection process does treat ephemeral generations differently. 479