Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't WeakReference a struct?

As this article says: http://www.philosophicalgeek.com/2014/08/14/prefer-weakreferencet-to-weakreference/

If you are using WeakReference at all, it likely means you are somewhat memory conscious . In this case, allocating new WeakReference objects will contribute extra, unnecessary memory pressure.

So in this case, wouldn't it make more sense to make it a struct? And immutable while we're at it, and get rid of SetTarget().

like image 449
benblo Avatar asked Jul 09 '15 14:07

benblo


People also ask

What's the difference between Softreference and Weakreference?

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.

What is Weakreference C#?

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.

What is Weakreference Java?

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.

Why do we use Weakreferences?

Notes. The reason you need a weak reference is so that the Garbage Collector can dispose of the objects when they are no longer needed. If two objects retain a strong reference to each other, then they can't be garbage collected. This is a memory leak.


1 Answers

The WeakReference and WeakReference<T> classes both have finalizers, which wouldn't be possible if they were structs.

If really necessary, you might be able to create your own custom weak-reference struct by making use of the weak variety of GCHandle. (I believe, though I'm not certain, that WeakReference and WeakReference<T> use GCHandle internally, although their finalizers ensure that everything is cleaned-up properly. Your custom struct would need to take care of its own clean-up without resorting to finalizers.)

like image 114
LukeH Avatar answered Oct 20 '22 22:10

LukeH