I understand and appreciate the usefulness of the System.WeakReference class in the .NET framework, but am curious as to the implementation details.
How is WeakReference implemented in .NET? MSDN discusses the usage of WeakReference in detail, but has little details that I've seen on how this works under the hood.
How does the CLR track the reference and know to null out the internal handle when the Target is collected, without preventing the GC? Does it require special handling in the CLR itself?
My main concern would be whether there are performance implications of using WeakReferences (especially if using many of them) that differ from those of using standard object references.
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
Weak references are all about garbage collection. A standard object will not "disappear" until all references to it are severed, this means all the references your various objects have to it have to be removed before garbage collection will consider it garbage.
The difference between a weak and a strong reference to an object is that while the former still allows the garbage collector to reclaim the memory occupied by that object, a strong reference to an object doesn't allow the garbage collector to reclaim the memory occupied by that object if the object is reachable.
A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC.
The WeakReference class hands off its object reference to the GC and gets a handle back. Whenever you get the reference or check if the reference is alive, the handle is used to ask the GC for the reference.
This means that the GC keeps a list of all weak references, which it has to update when objects are collected. It also means that there is some overhead every time you use a weak reference.
So, every weak reference means a little more work for the garbage collector, but on the other hand so does every regular reference too, even if it's less. You should of course be a bit careful about using a lot of weak references, but if you need that to get the memory management to work well with your objects, that should outweight the small overhead that it causes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With