Issue
I was recently wondering if there is any drawback for Set<Weakref<T>>
over WeakSet<T>
.
Pros:
- The set is iterable
Cons:
- The set must be filtered from no longer valid references
Am I missing something or is this almost a win-win situation? Would the Set<Weakref<T>>
version prevent the garbage collector from collecting?
Solution
What you missed:
WeakSets are collections of objects only. They cannot contain
arbitrary values of any type, as Sets can.The number of objects or their traversal order is immaterial, so a
WeakSet is more suitable (and performant) than a Set for tracking
object references, especially if a very large number of objects is
involved.
Set<Weakref<T>>
will not prevent GC. Also note that WeakRef
is not supported in Opera but WeakSet
is.
Answered By – windm
Answer Checked By – Marie Seifert (BugsFixing Admin)