WeakRef 不能自动回收 WebGL 纹理,需配合强引用缓存、弱引用追踪、使用计数和懒卸载调度实现惰性加载-自动回收;纹理句柄封装 JS 控制对象,WeakRef 标记可丢弃,GC 后调用 gl.deleteTexture 释放 GPU 内存。

WeakRef 本身不能直接实现自动回收,它只是提供一种不阻止垃圾回收的引用方式;真正的“惰性加载-自动回收”纹理池,需要 WeakRef 配合资源状态管理、使用计数、显式卸载策略和 GC 友好设计共同完成。
核心思路:用 WeakRef 标记“可丢弃”,而非“自动释放”
WebGL 纹理对象(WebGLTexture)本身不是 JS 垃圾可回收对象——它绑定在 GPU 上,JS 层的 Texture 实例只是控制句柄。WeakRef 能弱持有这个 JS 句柄,但不会触发 GPU 内存释放。因此关键在于:
- 把纹理 JS 对象(含 gl texture ID、尺寸、格式等元数据)封装为一个可被 WeakRef 弱引用的“纹理句柄”
- 用 Map 存储强引用的活跃句柄,并通过 WeakRef 关联到外部使用者(如 Mesh、Material),用于探测是否还在被 JS 层使用
- 定期轮询 WeakRef.deref() 返回 null 的句柄,再调用
gl.deleteTexture()彻底释放 GPU 资源 - 加载时先查缓存,命中则复用;未命中则加载并加入强引用池,同时返回一个 WeakRef 包装的访问代理
纹理池结构设计(精简版)
一个实用的池类需包含四层职责:
-
强引用缓存:
Map<string, TextureHandle>,键为纹理路径或哈希,值为完整句柄(含 gl texture、宽高、mipmap 状态等) -
弱引用追踪器:
Map<TextureHandle, WeakRef<TextureHandle>>,记录哪些句柄正被外部弱持有(用于后续清理判断) -
使用计数器(可选但推荐):
Map<TextureHandle, number>,每次 get +1,每次 release -1;仅当计数归零且 WeakRef 已失效时才真正删除 - 懒卸载调度器:不立即 deleteTexture,而是推入待卸载队列,在空闲帧(requestIdleCallback)或下一帧 render 之前批量执行,避免阻塞渲染
关键操作示例(TypeScript 片段)
以下为获取与释放的核心逻辑示意(省略加载细节):
// 获取纹理(惰性加载 + 复用)
async get(url: string): Promise<TextureRef> {
let handle = this.strongCache.get(url);
if (!handle) {
handle = await this.loadTexture(url); // 加载并创建 WebGLTexture
this.strongCache.set(url, handle);
this.weakTracker.set(handle, new WeakRef(handle));
}
this.useCount.set(handle, (this.useCount.get(handle) || 0) + 1);
return new TextureRef(handle, () => this.release(url));
}
<p>// TextureRef 是轻量代理,只暴露只读属性和绑定方法
class TextureRef {
constructor(
private handle: TextureHandle,
private onRelease: () => void
) {}</p><p>get id() { return this.handle.glTexture; }
get width() { return this.handle.width; }
// ……其他只读字段</p><p>bind(unit: number) {
this.handle.bind(unit); // 调用 WebGL 绑定逻辑
}
}</p><p>// 显式释放(非强制,仅提示“不再需要”)
release(url: string) {
const handle = this.strongCache.get(url);
if (!handle) return;
const count = this.useCount.get(handle) || 0;
if (count <= 1) {
this.useCount.delete(handle);
// 检查是否已无 JS 强引用且 WeakRef 失效
if (!this.weakTracker.get(handle)?.deref()) {
this.pendingDeletions.push(handle);
}
} else {
this.useCount.set(handle, count - 1);
}
}
配合 GC 的实践要点
WeakRef 的实际回收时机不可控,需主动配合提升有效性:
- 避免在闭包中长期强持有 TextureHandle(例如 Material 实例不应保存 handle 引用,而应保存 url + ref 代理)
- Mesh/Model 实例统一通过
TextureRef访问纹理,且在销毁自身时调用ref.dispose()(即触发 release) - 每帧开始前运行一次清理:遍历
pendingDeletions,对每个 handle 执行gl.deleteTexture(handle.glTexture),然后从 strongCache、weakTracker、useCount 中彻底移除 - 开发期可用
performance.memory或 Chrome 的 Memory tab 观察纹理句柄数量趋势,验证弱引用是否按预期失效

















