Weak Maps

Whether entries follow the object or the map — PHP 8 WeakMap against GC-cooperative caching in 10 languages.

C C23

C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* C has no GC and therefore no weak references; "forgetting" an object is
   manual: clear the handle, free the storage yourself */
typedef struct {
    char *name;
} Obj;

int main(void) {
    Obj *o = malloc(sizeof(Obj));
    o->name = strdup("thing");

    /* a side table keyed by the raw pointer — a strong reference, unlike a
       WeakMap; entries must be removed by hand before freeing */
    printf("entry present: %s\n", o->name);

    free(o->name);
    free(o);            /* any map entry would now dangle if kept */
    o = NULL;
    printf("entry present: %s\n", o ? "yes" : "no");
    return 0;
}
Output
entry present: thing
entry present: no

C++ C++26

C++26
#include <cstdio>
#include <memory>

int main() {
    std::weak_ptr<int> weak;
    {
        auto shared = std::make_shared<int>(7);
        weak = shared;
        std::printf("alive, value %d\n", *weak.lock());
    } // the strong reference dies here
    std::printf("expired: %s\n", weak.expired() ? "true" : "false");
    return 0;
}
Output
alive, value 7
expired: true

C# v11.0.100

v11.0.100
using System;
using System.Linq;
using System.Runtime.CompilerServices;

Store.Attach();
Console.WriteLine("entries: " + Store.Table.Count());
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.WriteLine("entries: " + Store.Table.Count());

class Key { }

class Store
{
    internal static readonly ConditionalWeakTable<Key, string> Table = new();

    [MethodImpl(MethodImplOptions.NoInlining)]
    internal static void Attach()
    {
        Table.Add(new Key(), "metadata"); // the Key lives only in the weak key slot
    }
}
Output
entries: 1
entries: 0

Go v1.27.4

v1.27.4
package main

import "fmt"

type User struct{ Name string }

// Go has no weak references; a plain map keeps keys alive until deleted
// explicitly — caching by identity needs manual eviction
func main() {
	m := map[*User]string{}
	u := &User{Name: "ada"}
	m[u] = "metadata"
	fmt.Println("entries:", len(m))
	delete(m, u) // the cleanup the GC would do for you in other languages
	u = nil
	fmt.Println("entries:", len(m))
}
Output
entries: 1
entries: 0

Java v27.0.1

v27.0.1
import java.util.WeakHashMap;

public class Main {
    // create the key in a helper frame so it holds no local reference after
    static void seed(WeakHashMap<Object, String> m) {
        m.put(new Object(), "metadata");
    }

    public static void main(String[] args) throws Exception {
        WeakHashMap<Object, String> m = new WeakHashMap<>();
        seed(m);
        System.out.println("entries: " + m.size());
        // the collector runs at the scheduler's mercy; nudge it until the
        // stale entry is expunged (deterministic end state)
        for (int i = 0; i < 50 && m.size() > 0; i++) {
            System.gc();
            Thread.sleep(10);
        }
        System.out.println("entries: " + m.size());
    }
}
Output
entries: 1
entries: 0

JavaScript v26.13.1

v26.13.1
// WeakMap keys are held weakly: entries vanish when the GC reclaims the
// key — timing is the collector's business, not ours
const cache = new WeakMap();
const user = { name: "ada" };
cache.set(user, "metadata");
console.log("has:", cache.has(user), "value:", cache.get(user));
cache.delete(user);
console.log("has after delete:", cache.has(user));
Output
has: true value: metadata
has after delete: false

PHP v8.6.0

v8.6.0
class Node {
    public ?Node $peer = null;
    public function __destruct() { echo "collected\n"; }
}

$wm = new WeakMap();
$a = new Node();
$b = new Node();
$a->peer = $b;
$b->peer = $a;      // a reference cycle: refcounts keep each other alive

$wm[$a] = "metadata";
echo "entries: ", count($wm), "\n";

$a = $b = null;     // drop the last external references
echo "before gc: ", count($wm), "\n";
gc_collect_cycles(); // the collector breaks the cycle, WeakMap sheds its entry
echo "after gc: ", count($wm), "\n";
Output
entries: 1
before gc: 1
collected
collected
after gc: 0

Python v3.15.2

v3.15.2
import weakref
import gc

class User:
    pass

cache = weakref.WeakKeyDictionary()
u = User()
cache[u] = "metadata"
print("entries:", len(cache))
del u
gc.collect()  # CPython refcounting already reclaimed it; this is belt and braces
print("entries:", len(cache))
Output
entries: 1
entries: 0

Rust v1.99.1

v1.99.1
use std::rc::{Rc, Weak};

fn main() {
    let weak: Weak<String>;
    {
        let strong = Rc::new("metadata".to_string());
        weak = Rc::downgrade(&strong);
        println!("alive: {}", weak.upgrade().is_some());
    } // the strong count drops to zero here
    println!("alive: {}", weak.upgrade().is_some());
}
Output
alive: true
alive: false

TypeScript v26.13.1

v26.13.1
// typed WeakMap: the key type is checked at compile time, the GC still
// decides when entries disappear
class User { name = "ada"; }
const cache = new WeakMap<User, string>();
const user = new User();
cache.set(user, "metadata");
console.log("has:", cache.has(user), "value:", cache.get(user));
cache.delete(user);
console.log("has after delete:", cache.has(user));
Output
has: true value: metadata
has after delete: false

Language differences

C: no GC means no weak references (example): forgetting an object is manual — clear the handle and free the storage yourself; a side table keyed by the raw pointer is a strong reference whose entries outlive the object, hand-cleanup or they dangle.

C++: std::weak_ptr (example): the standard weak side of shared_ptr, with lock() probing losslessly and expired() checking death; when scope ends the strong count hits zero and the weak side notices immediately — determinism comes from reference counting, not GC.

C#: ConditionalWeakTable (example): weakly-held keys whose entries vanish with GC; the sample keeps the key alive only in the weak key slot via a NoInlining method, and GC.Collect deterministically converges to 0.

Go: no weak references (example): map[*T]V keeps key objects alive forever, so identity-keyed caches need manual delete — the absence is a long-standing pain point in the Go ecosystem (an open proposal for years).

Java: WeakHashMap (example): the classic weakly-keyed map; entries are expunged on the next access after GC; timing follows the collector, and the sample converges to a deterministic end state with a gc polling loop.

JavaScript: the built-in WeakMap (example): keys must be objects and are held weakly; entries vanish when the key is reclaimed, on the GC's schedule — the sample shows only the deterministic behavior while the key lives (set/get/has/delete).

PHP: 8.0+ WeakMap (example): object keys that do not count toward refcounts, entries shed when the object dies; the sample deliberately builds a reference cycle — after the external references drop, the pair survives until gc_collect_cycles() breaks it, and destruction and entry removal happen together; WeakMap implements ArrayAccess/Countable/IteratorAggregate, so it reads like an associative array.

Python: weakref.WeakKeyDictionary (example): a weakly-keyed dictionary; CPython refcounting reclaims on del immediately, so the entry vanishes right away — more deterministic than chasing GC timing.

Rust: Weak paired with Rc (example): downgrade creates the weak side and upgrade() probes liveness; scope end drops the strong count and upgrade returns None — fully deterministic, because reclamation is deterministic.

TypeScript: the typed WeakMap (example): identical runtime semantics to JS; the generic key type is validated at compile time while the GC still decides the entry lifecycle.