Chuyển đến nội dung

Bài 29 · Concurrency and Memory

The Garbage Collector in D

Understand D's garbage collector: how mark-and-sweep works, what allocates, GC.collect and GC.stats, @nogc code, tuning and avoiding pauses, with a runnable C mark-and-sweep simulator.

D is a systems language with a garbage collector (GC) on by default. You allocate with new, array appends, closures and associative arrays; the runtime frees memory once nothing can reach it. This makes everyday code safe and short, and D gives you the means to turn the collector off for the parts of the program where it matters.

D code is read-only on this site. The runnable program is a C mark-and-sweep simulator: a tiny object heap with roots, references, a collection phase and printed statistics. It is a teaching model, not D's actual collector.

What allocates from the GC

D
auto obj  = new MyClass();        // class instance
int[] a   = new int[100];         // dynamic array
a ~= 5;                           // may reallocate
string s  = "x" ~ name;           // concatenation allocates
auto dg   = () => capturedVar;    // closure context may be heap-allocated
int[string] map; map["k"] = 1;    // associative array

Slices (a[2 .. 5]) do not allocate: they are a pointer and a length into existing memory. Many standard library range algorithms are lazy for the same reason.

How the collector works

The D GC is a conservative, stop-the-world, mark-and-sweep collector:

  1. Mark. Start from the roots (global data, thread stacks, registers) and follow every pointer into the GC heap, marking what is reachable.
  2. Sweep. Everything unmarked is garbage; return it to the free lists.

It is conservative: any word that looks like a pointer into the heap keeps that block alive, even if it is really an integer. It is stop-the-world: while it runs, all threads that the runtime knows about are paused. A collection happens when an allocation cannot be satisfied from free memory, or when you ask for it.

flowchart LR
    R["Roots: stacks, globals"] --> A["Object A"]
    A --> B["Object B"]
    R --> C["Object C"]
    D["Object D"] --> E["Object E"]
    style D fill:#fdd
    style E fill:#fdd

A, B and C are reachable and survive. D and E refer only to each other and are garbage.

A mark-and-sweep simulation

The simulator below has ten heap slots. Each object may point to two others. Some are roots. After collect() the unreachable ones are freed, including a cycle: reference counting cannot free cycles, but a tracing collector can.

C Stand-in: mark and sweep on a tiny heap

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Controlling the GC from D

D
import core.memory;

GC.collect();            // run a collection now
GC.minimize();           // return free pages to the OS
GC.disable();            // no automatic collections (until enable())
GC.enable();
auto s = GC.stats();     // usedSize, freeSize
auto p = GC.malloc(1024);// raw GC memory
GC.free(p);              // free early (you must be sure nothing uses it)

Disabling the GC during a latency-critical burst, then calling GC.collect() at a quiet moment, is a legitimate technique. You can also set options at start-up: extern(C) __gshared string[] rt_options = ["gcopt=initReserve:64 profile:1"]; or with the DRT_GCOPT environment variable (profile:1 prints collection statistics at exit).

@nogc

Mark a function @nogc and the compiler proves it never allocates from the GC. Calling new, appending to a dynamic array, or using a closure that needs the heap becomes a compile error.

D
@nogc nothrow int sum(const int[] values)
{
    int total;
    foreach (v; values) total += v;
    return total;
}

Use @nogc in hot loops, audio callbacks, interrupt-like code, and library code that wants to be usable by every caller. Manual alternatives are core.stdc.stdlib.malloc, std.experimental.allocator, stack arrays, and scope allocations (see scope and RAII).

Practical advice

  • Reuse buffers. Keep a long-lived array and reset its length with a.length = 0; a.assumeSafeAppend();.
  • Prefer slices and lazy ranges to avoid copies.
  • Preallocate with reserve: a.reserve(10_000).
  • Avoid GC use in tight loops; profile with -profile=gc, which lists every allocation site.
  • Do not store GC pointers in malloc'd memory unless you register it with GC.addRange; the collector cannot see it and may free what is still in use.
  • Do not rely on destructors of classes for cleanup; they run when the object is collected (see classes).

Counting allocations in C

A rough habit from D transfers to any language: know where allocation happens. The program counts a few allocations made while building a growing array and shows why reserving capacity helps.

C Stand-in: growth strategy and reallocation count

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

D's array append uses an over-allocation strategy like the doubling case, which is why appending in a loop is cheap on average.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which of these does NOT allocate GC memory?

    A slice is just a pointer plus length into existing memory.
  2. 2. What does a conservative collector do with an integer that looks like a heap address?

    It cannot tell integers from pointers, so it may retain memory unnecessarily.
  3. 3. What does @nogc guarantee?

    It is a compile-time guarantee about GC allocation, not a runtime switch.
  4. 4. Why can tracing collectors free cycles that reference counting cannot?

    Reachability from roots, not a count, decides survival.

Summary

  • D's GC is conservative, stop-the-world mark and sweep; new, appends, closures and AAs allocate.
  • GC.collect, GC.disable, GC.stats and gcopt let you control and observe it.
  • @nogc code is proven allocation-free; reuse buffers and reserve capacity otherwise.
  • Do not depend on class destructors for cleanup.

Next: scope, RAII and Manual Memory

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.