弱引用映射

条目跟着对象走还是跟着映射走——PHP 8 WeakMap 与 10 语言 GC 协作缓存对照。

C C23

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

/* C 没有 GC,因此也没有弱引用;「遗忘」对象全靠手工:
   清掉句柄、自己释放存储 */
typedef struct {
    char *name;
} Obj;

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

    /* 以裸指针为键的旁表——与 WeakMap 不同,这是强引用;
       释放前必须手工移除条目 */
    printf("entry present: %s\n", o->name);

    free(o->name);
    free(o);            /* 若保留条目,此刻它已悬空 */
    o = NULL;
    printf("entry present: %s\n", o ? "yes" : "no");
    return 0;
}
输出
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());
    } // 强引用在此死亡
    std::printf("expired: %s\n", weak.expired() ? "true" : "false");
    return 0;
}
输出
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"); // Key 只活在弱键槽里
    }
}
输出
entries: 1
entries: 0

Go v1.27.4

v1.27.4
package main

import "fmt"

type User struct{ Name string }

// Go 没有弱引用;普通 map 会一直保活键对象,直到显式删除——
// 按身份缓存需要手工淘汰
func main() {
	m := map[*User]string{}
	u := &User{Name: "ada"}
	m[u] = "metadata"
	fmt.Println("entries:", len(m))
	delete(m, u) // 这一步在其他语言里由 GC 代劳
	u = nil
	fmt.Println("entries:", len(m))
}
输出
entries: 1
entries: 0

Java v27.0.1

v27.0.1
import java.util.WeakHashMap;

public class Main {
    // 在辅助帧里创建键,返回后不再持有局部引用
    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());
        // 收集器听调度器安排;持续轻推直到过期条目被清除
        //(确定性终态)
        for (int i = 0; i < 50 && m.size() > 0; i++) {
            System.gc();
            Thread.sleep(10);
        }
        System.out.println("entries: " + m.size());
    }
}
输出
entries: 1
entries: 0

JavaScript v26.13.1

v26.13.1
// WeakMap 的键是弱持有的:GC 回收键对象时条目随之消失——
// 时机由收集器说了算,不由我们说了算
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));
输出
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;      // 引用环:引用计数互相保活

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

$a = $b = null;     // 丢掉最后的外部引用
echo "before gc: ", count($wm), "\n";
gc_collect_cycles(); // 收集器拆环,WeakMap 随之甩掉条目
echo "after gc: ", count($wm), "\n";
输出
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 引用计数早已回收它;这里是双保险
print("entries:", len(cache))
输出
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());
    } // 强引用计数在此归零
    println!("alive: {}", weak.upgrade().is_some());
}
输出
alive: true
alive: false

TypeScript v26.13.1

v26.13.1
// 类型化 WeakMap:键类型编译期检查,条目何时消失
// 仍由 GC 决定
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));
输出
has: true value: metadata
has after delete: false

语言差异说明

C:无 GC 即无弱引用(示例):「遗忘」对象是手工活——清句柄、自己 free;以裸指针为键的旁表是强引用,条目不会随对象消失,需手工清理(否则悬空)。

C++:std::weak_ptr(示例):与 shared_ptr 配对的标准弱引用,lock() 无损探测、expired() 查死亡;作用域结束强计数归零,弱侧立刻观察到——确定性来自引用计数而非 GC。

C#:ConditionalWeakTable(示例):键弱持有、随 GC 回收条目消失;示例用 NoInlining 方法让键只活在弱键槽里,GC.Collect 后确定收敛到 0。

Go:无弱引用(示例):map[*T]V 永久保活键对象,按身份缓存必须手工 delete——弱引用的缺失是 Go 生态缓存的长期痛点(官方议题多年未决)。

Java:WeakHashMap(示例):键弱持有的经典实现,GC 后条目在下一次访问时清除;清除时机取决于收集器,示例用 gc 轮询循环收敛到确定性终态。

JavaScript:内建 WeakMap(示例):键只能是对象且弱持有,条目随键回收消失;时机由 GC 决定——示例只演示键存活期的确定行为(set/get/has/delete)。

PHP:8.0+ WeakMap(示例):对象为键、不计入引用计数;条目随对象回收消失。示例特意造引用环:外部引用清零后仍存活,gc_collect_cycles() 拆环时析构与条目清除同时发生——WeakMap implements ArrayAccess/Countable/IteratorAggregate,用法接近关联数组。

Python:weakref.WeakKeyDictionary(示例):弱键字典,CPython 引用计数让 del 后立即回收,条目即时消失——比追 GC 时机更确定。

Rust:Weak/Rc 配对(示例):downgrade 造弱引用、upgrade() 探活;作用域结束强计数归零,upgrade 返回 None——完全确定,因为回收是确定性的。

TypeScript:类型化 WeakMap(示例):与 JS 同一运行时语义;泛型键类型在编译期校验,条目生命周期仍由 GC 决定。