[SOLVED] Difference between WeakSet<T> and Set<Weakref<T>>

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.

MDN source

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)

Leave a Reply

Your email address will not be published. Required fields are marked *