Memory and garbage collection

suggest change

The Dart runtime employs an automated memory management system featuring an efficient, generational garbage collector (GC) tailored specifically for high-frame-rate user interfaces (Flutter) and reactive server-side isolates.

Understanding how Dart allocates memory, reclaims unused objects, and structures heaps is essential for eliminating memory leaks and avoiding GC pauses ("jank").


The Dart Memory Architecture

1. Isolated Heaps

A fundamental architectural principle of Dart is that each Isolate possesses its own completely private heap:

2. Generational Garbage Collection

Dart's memory allocator partitions the heap into two generations:

+-------------------------------------------------------+
|                    Dart Isolate Heap                  |
|                                                       |
|  +---------------------------+  +------------------+  |
|  |     Young Generation      |  |  Old Generation  |  |
|  |  (Scavenger / Semi-Space) |  |   (Mark-Sweep)   |  |
|  |  - Fast bump allocation   |  |  - Promoted      |  |
|  |  - Ephemeral objects      |  |    survivors     |  |
|  |  - Cleans up in < 1ms     |  |  - Concurrent    |  |
|  +---------------------------+  +------------------+  |
+-------------------------------------------------------+
  1. Young Generation (Nursery / Scavenger):

    • Optimized for short-lived, ephemeral objects (such as Flutter UI widgets and temporary stack variables created during layout/paint).
    • Uses a semi-space copying scavenger: Active objects are copied into an alternate memory region, and dead memory is reclaimed immediately in bulk.
    • Allocations use a simple bump-pointer, making allocation as fast as a pointer increment (under 1–2 milliseconds).
  2. Old Generation (Mark-Sweep / Mark-Compact):

    • Objects that survive multiple young-generation scavenge cycles are promoted to the Old Generation.
    • Collected using a concurrent mark-sweep / compacting collector that runs largely in the background to prevent user interface stutter.

Const Canonicalization

Dart's const keyword enables compile-time canonicalization:

class Configuration {
  final String environment;
  final int timeoutSeconds;

  const Configuration({required this.environment, required this.timeoutSeconds});
}

void main() {
  // Both point to the exact same memory address (identical instance)
  const configA = Configuration(environment: 'production', timeoutSeconds: 30);
  const configB = Configuration(environment: 'production', timeoutSeconds: 30);

  print(identical(configA, configB)); // true
}

By reusing canonical const objects across the application, the Dart VM avoids allocating duplicate objects and completely bypasses garbage collection for those instances.


Weak References and Finalizers

Dart provides modern low-level memory primitives in dart:core to interact safely with the GC.

WeakReference<T>

A WeakReference holds an object reference that does not prevent the target object from being reclaimed by the garbage collector:

class ImageBitmap {
  final String id;
  final List<int> pixelData;
  ImageBitmap(this.id, this.pixelData);
}

class ImageCache {
  final Map<String, WeakReference<ImageBitmap>> _cache = {};

  void put(String id, ImageBitmap bitmap) {
    _cache[id] = WeakReference(bitmap);
  }

  ImageBitmap? get(String id) {
    final ref = _cache[id];
    final bitmap = ref?.target;

    if (bitmap == null) {
      _cache.remove(id); // Target was garbage-collected
      return null;
    }
    return bitmap;
  }
}

Finalizer<T>

A Finalizer executes a callback after an object has been garbage-collected, useful for releasing non-Dart resources (such as native FFI memory buffers, file handles, or C library pointers):

import 'dart:ffi';
import 'package:ffi/ffi.dart';

// Native resource wrapper
class NativeBuffer {
  Pointer<Uint8> pointer;

  static final Finalizer<Pointer<Uint8>> _finalizer = Finalizer((ptr) {
    print('Finalizer called: Freeing native buffer at $ptr');
    calloc.free(ptr);
  });

  NativeBuffer(int size) : pointer = calloc<Uint8>(size) {
    // Attach finalizer to this instance
    _finalizer.attach(this, pointer, detach: this);
  }

  void close() {
    if (pointer != nullptr) {
      _finalizer.detach(this);
      calloc.free(pointer);
      pointer = nullptr;
    }
  }
}

Preventing Common Memory Leaks

1. Uncanceled Stream Subscriptions

Streams and event buses hold references to listening closures. If a subscription is never canceled, the listener and any object referenced within its closure cannot be garbage collected:

import 'dart:async';

class SensorMonitor {
  final Stream<double> sensorStream;
  StreamSubscription<double>? _subscription;

  SensorMonitor(this.sensorStream);

  void startListening() {
    _subscription = sensorStream.listen((reading) {
      _processReading(reading);
    });
  }

  void _processReading(double val) {
    print('Reading: $val');
  }

  // Always dispose and cancel subscriptions
  void dispose() {
    _subscription?.cancel();
    _subscription = null;
  }
}

2. Closures Capturing Outer this

When passing callbacks, be aware that capturing instance methods or referencing this keeps the outer instance alive:

class HeavyService {
  final List<int> largePayload = List.filled(1000000, 1);

  void register(EventBus bus) {
    // LEAK RISK: Storing this lambda retains HeavyService indefinitely
    bus.onEvent = () {
      print("Event fired, payload size: ${largePayload.length}");
      // Referencing a field implicitly captures `this`!
    };
  }
}

To prevent unintentional retention, pass static or top-level functions or clear handlers when tearing down.


Profiling with Dart DevTools

The Dart DevTools suite provides comprehensive real-time heap analysis:

  1. Memory View: Displays current heap size, RSS (Resident Set Size), and garbage collection events over time.
  2. Heap Snapshot: Captures all live objects in memory. You can compare two snapshots to detect which objects were allocated between actions and failed to be collected.
  3. Retaining Path: Clicking any object in a heap snapshot displays the chain of references holding it in memory, pinpointing which static list, stream, or closure is preventing GC.

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents