liveBook · Manning

Compaction

As explained in .NET in Action, Second Edition

Garbage-collection compaction moves live objects together to reduce fragmentation and create larger contiguous free-memory regions.

Compaction moves live objects together on the .NET heap to create a larger contiguous region of free memory. It matters when an allocation needs one unbroken chunk, not merely enough free space in total. section 10.3.4

Imagine a 1 MB heap filled with successive allocations. Garbage collection frees unused chunks, but the gaps between live chunks may still be too small for a new array. Compacting the live chunks brings the free space together. section 10.3.4

Figure 10.9 The heap after compaction

The heap after compaction shows why moving live chunks can make a previously impossible allocation fit. section 10.3.4

Moving arrays matters when code uses pointers to their memory. In an `unsafe` copy routine, `fixed` keeps the source and target arrays at the same physical locations until the block finishes, so compaction cannot move them during the pointer-based copy. section 10.3.4

Listing 10.10 C# copy array using pointers instead of references
int[] CopyArray(int[] source)
{
  int length = source.Length;
  int[] target = new int[length];           #1
  unsafe                                    #2
  {
    fixed (int* pSource = source,           #3
           int* pTarget = target)
    {
      for (int i = 0; i < length; i++)
      {
        pTarget[i] = pSource[i];            #4
      }
    }
  }
  return target;                            #5
}

The pointer-based array copy places both arrays inside a `fixed` block before accessing their elements. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Works through allocation, collection, and compaction on a 1 MB heap, then relates movement to `fixed`; does not detail collector internals.
Examples
Uses a 1 MB heap allocation sequence, a heap-after-compaction figure, and a pointer-based array copy.
What it assumes
Assumes familiarity with C# arrays while introducing heap allocation, collection, and pinning through a concrete scenario.
What you can do after
Diagnose/debug with it why free heap space may not satisfy an allocation and why pointer-based array access requires `fixed`.
How it connects
Connects compaction to heap fragmentation, garbage collection, contiguous allocation, reference types, unsafe pointers, and pinning.

Also explained in

Compare how 5 books explain compaction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.