Other uses of weak references?
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?
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.
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.
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.
下一篇: 弱引用的其他用途?