Free mag vol1 | Page 535

CHAPTER 13  UNDERSTANDING OBJECT LIFETIME IL_0006: stloc.0 IL_0007: ret } // end of method Program::MakeACar Before we examine the exact rules that determine when an object is removed from the managed heap, let’s check out the role of the CIL newobj instruction in a bit more detail. First, understand that the managed heap is more than just a random chunk of memory accessed by the CLR. The .NET garbage collector is quite a tidy housekeeper of the heap, given that it will compact empty blocks of memory (when necessary) for purposes of optimization. To aid in this endeavor, the managed heap maintains a pointer (commonly referred to as the next object pointer or new object pointer) that identifies exactly where the next object will be located. That said, the newobj instruction tells the CLR to perform the following core operations: • Calculate the total amount of memory required for the object to be allocated (including the memory required by the data members and the base classes). • Examine the managed heap to ensure that there is indeed enough room to host the object to be allocated. If there is, the specified constructor is called and the caller is ultimately returned a reference to the new object in memory, whose address just happens to be identical to the last position of the next object pointer. • Finally, before returning the reference to the caller, advance the next object pointer to point to the next available slot on the managed heap. The basic process is illustrated in Figure 13-2. Figure 13-2. The details of allocating objects onto the managed heap As your application is busy allocating objects, the space on the managed heap may eventually become full. When processing the newobj instruction, if the CLR determines that the managed heap does not have sufficient memory to allocate the requested type, it will perform a garbage collection in an attempt to free up memory. Thus, the next rule of garbage collection is also quite simple:  Rule If the managed heap does not have sufficient memory to allocate a requested object, a garbage collection will occur. 476