Skip to content

Memory Management

Wyn uses Automatic Reference Counting (ARC). Every heap-allocated value (strings, arrays, HashMaps) has a reference count. When the count reaches zero, the memory is freed immediately.

How It Works

wyn
fn main() -> int {
    var s = "hello"       // RC = 1
    var t = s             // RC = 2 (shared reference)
    // t goes out of scope → RC = 1
    // s goes out of scope → RC = 0 → freed
    return 0
}

You don't manage memory manually. The compiler inserts retain/release calls automatically.

Scope-Based Cleanup

Strings, arrays, and HashMaps are freed at block exit:

wyn
fn process() -> int {
    var items = "a,b,c".split(",")   // Array allocated
    var upper = "hello".upper()       // String allocated
    var m = {"key": "value"}          // HashMap allocated
    // ... use them ...
    return 0
}   // items, upper, m all freed here

String Optimizations

Wyn's RC header caches string length and capacity:

  • .len() is O(1) — reads cached length, no strlen scan
  • String append (s = s + "x") is O(1) amortized — reuses buffer when refcount is 1
  • Method chains (s.upper().trim()) release intermediates automatically

Zero Leaks

v1.10 has zero known memory leaks. All patterns are verified with AddressSanitizer:

  • String concat temporaries
  • Function argument temporaries
  • Method chain intermediates
  • Unused return values
  • Array and HashMap scope cleanup

Thread Safety

Reference counting uses atomic operations. Strings can be safely shared across spawn boundaries. The RC system uses memory_order_acq_rel for release and memory_order_relaxed for retain.

MIT License