Other uses of weak references?

2019-04-07 03:46发布

问题:

I know that weak references are a good candidate for memoizing potentially large sets of data, and Wikipedia's article on weak references only lists "keeping track of the current variables being referenced in the application" and the statement "Another use of weak references is in writing a cache".

What are some other situations (more specific than just "caching results") where the use of weak references is A Good IdeaTM?

回答1:

In Flex, use weak references to avoid memory leaks.

If an event handler is a member of a short-lived instance object, passing the handler as a strong reference to an object which will live longer may keep the short-lived instance alive unnecessarily.



回答2:

I use weak references for a few things...

I like to create "Weak Events" in .Net to avoid observables from keeping observers alive too long.

I have also used weak events to detect memory leaks.



回答3:

The primary correct use for weak references is to identify things whose importance derives from the existence of strong references to them. The two most common scenarios are either:

  • An object holds a reference to something not because it "cares" about the object in question, but rather because other entities which do care about the object might want it to do something with it. If after awhile nobody cares about the object anymore, there's no reason why other entities should continue to manipulate it on behalf of "all the entities that care about it".

  • The memory cost of holding many references to the same immutable object may be much lower than the memory cost of holding references to many identical objects, and comparing references to the same object may be be much faster than comparing identical objects. The memory cost of creating an immutable object, abandoning it, having it get collected, and creating an identical object is essentially the same as the cost of creating an object and later returning a second reference to it. Returning a reference to an existing object which would have to be retained anyway is a big win; returning a reference to an object which was eligible for collection but hadn't been collected yet may or may not be a win (it's usually a slight win, but in a generational GC it can sometimes hurt performance slightly); in many cases, the latter benefits would not be sufficient to justify keeping an object alive longer than would otherwise be necessary.



回答4:

In Python, the garbage collector uses reference counting to decide when to "destroy" or otherwise deallocate an object. A normal circular reference can result in objects never being garbage collected because their reference counts respectively stay at 1 or higher; but using weak references will allow both/all objects to be properly cleaned up when they go out of scope.