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 总是为相同属性集返回相同的对象,但不再需要的那些值不会永远保留在缓存中。