class ObjectSpace::WeakKeyMap

ObjectSpace::WeakKeyMap 是一个键值映射,它对其键持有弱引用,因此当不再有引用时,它们可以被垃圾回收。

ObjectSpace::WeakMap 不同的是:

(请注意,此处使用 GC.start 仅用于演示目的,可能并不总是能得到演示的结果。)

该集合特别适用于实现轻量级值对象的缓存,这样每个值的表示形式在内存中只会存储一份,而不再使用的副本将被垃圾回收。

CACHE = ObjectSpace::WeakKeyMap

def make_value(**)
   val = ValueObject.new(**)
   if (existing = @cache.getkey(val))
      # if the object with this value exists, we return it
      existing
   else
      # otherwise, put it in the cache
      @cache[val] = true
      val
   end
end

这将导致 make_value 始终为同一组属性返回相同的对象,但不再需要的值不会永远保留在缓存中。