Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Memory and Concurrency

Memory Management with ARC and ORC in Nim

Learn how Nim frees memory without a tracing garbage collector, how ARC and ORC use reference counting and destructors, and what move semantics mean, with C stand-ins.

Nim manages memory for you, but not with the pause-prone garbage collector you may know from Java or Go. Modern Nim (version 2 and later) uses ARC and ORC by default (--mm:orc): deterministic, scope-based memory management built on destructors and reference counting. Memory is released at predictable points, there are no stop-the-world pauses, and the design suits games, embedded systems and servers.

The real compiler is not available on this site, so the Nim code is read-only. The C stand-ins reproduce the mechanisms by hand.

Scope-based destruction

Every type that owns a resource has a destructor: a hook that the compiler calls when the last owner goes out of scope. For seq, string and ref types the standard library provides them, so you rarely write one.

NIM
type
  Buffer = object
    data: ptr UncheckedArray[byte]
    size: int

proc `=destroy`(b: Buffer) =
  if b.data != nil:
    dealloc(b.data)

proc newBuffer(n: int): Buffer =
  Buffer(data: cast[ptr UncheckedArray[byte]](alloc(n)), size: n)

proc work() =
  let b = newBuffer(1024)
  echo b.size
  # `=destroy` is called here, automatically, when b leaves scope

work()

This is the same idea as RAII in C++. The compiler inserts the destructor call at the end of the scope, including on early return and when an exception unwinds the stack. The stand-in does it by hand with a cleanup call:

C C stand-in: allocate, use, release at scope end

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.

ARC: reference counting for ref types

For ref objects the compiler counts how many references exist. When the count reaches zero the object is destroyed at once. Because the counting is inserted by the compiler and optimized away where it can prove ownership, --mm:arc is cheap. The cost is that a cycle of references (a points to b, b points to a) never reaches zero.

flowchart LR
  A["Node a<br/>refcount 1"] --> B["Node b<br/>refcount 1"]
  B --> A

A cycle: neither count drops to zero, so ARC alone leaks it.

ORC is ARC plus a small cycle collector that runs only when it may find cycles. It is the default, so cyclic structures such as doubly linked lists and graphs just work.

C C stand-in: a reference 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.

Moves and copies

Assigning a value normally copies it. When the source is not used again, the compiler turns the copy into a move: the buffer changes owner without duplicating memory. The last use of a variable is detected automatically, and you can force a move with move(x) or sink parameters.

NIM
var a = @[1, 2, 3]
var b = a            # copy: a is used again below
echo a.len
let c = move(b)      # b is left empty, no allocation

Custom types can implement =copy, =sink and =destroy hooks, so a type can ban copying (=copy marked {.error.}) and be move-only, like a file handle or a unique pointer.

Choosing a memory manager

Switch Meaning
--mm:orc Default: ARC with a cycle collector
--mm:arc No cycle collection: smallest overhead, you avoid cycles
--mm:refc Legacy deferred reference counting garbage collector
--mm:none No memory manager (bare metal, advanced)

Share data across threads carefully: see Threads and Channels. For the difference between values and references, see Value, Reference and Pointer Semantics.

Common mistakes

  • Holding a ptr to memory owned by a seq that later grows: the buffer may move.
  • Creating cycles under --mm:arc and wondering about leaks; use ORC or break the cycle with a weak link (ptr or an index).
  • Expecting finalization order across modules; only scope order inside a procedure is guaranteed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which memory manager is the default in modern Nim?

    ORC is ARC plus a cycle collector and is the default since Nim 2.
  2. 2. When is a destructor called?

    The compiler inserts the call at scope end.
  3. 3. What problem does ARC alone have?

    Cycles keep counts above zero, which is why ORC adds a cycle collector.
  4. 4. What does move(x) do?

    A move hands over the buffer and leaves the source empty.

Summary

  • Nim frees memory deterministically through destructors, without a tracing collector.
  • ARC counts references on ref types; ORC adds cycle collection and is the default.
  • Moves transfer ownership; copy hooks can forbid copying.
  • Choose a manager with --mm:.

Next: Value, Reference and Pointer Semantics