Here's another use case for weak references that I don't think has been
mentioned yet:

Caching of expensive-to-recreate data. When working on frontend projects, I
quite frequently found myself in a situation where I had some data that I
could recreate, but where doing so would be at least moderately costly.
Examples of this are large-ish pieces of data loaded from the network/
cache, decompressed data or post-processed data. Crucially, I didn't know
how frequently I might need that data, as that depended on user actions.

Obviously, it's easy to implement caching strategies that apply some
heuristics like time since last access of the data. However, none of these
heuristics can take into account what the overall memory situation on the
device might be like. If my app is running in one of many tabs (or as one
of many applications on a mobile device), then I simply don't have the
required data at hand to make really useful decisions about when to evict
data from a cache.

The GC, OTOH, does have this information, and with weak references, I could
delegate the decision about when to evict something from the cache.

Note that I don't think that this in itself is a use case that'd justify
having weak references. I do think that it is a valid use case, and that,
if it came down to weighing the pros and cons (instead of vetoing the
feature on more fundamental grounds, which I can totally see making sense),
it would be a point in favor of them.


On Tue, Dec 3, 2013 at 8:37 PM, Boris Zbarsky <[email protected]> wrote:

> On 12/3/13 4:43 AM, Brendan Eich wrote:
>
>> Andrew McCreight wrote:
>>
>>> As far as I understand it, weak references are useful to avoid leaks
>>> when you don't know (1) who is referring to you or (2) what your
>>> lifetime should be.
>>>
>>
>> Yes. Doesn't nsIObserver still need XPCOM weak refs due to the
>> conjunction of (1) and (2)?
>>
>
> "Need" is a strong word.
>
> Our current view of weak nsIObserver is that they're an attractive
> nuisance that makes you think you can be lazy and don't need to
> removeObserver while in reality that just means you leak memory inside the
> observer service.... (though you don't leak your own memory).
>
> -Boris
>
> _______________________________________________
> dev-tech-js-engine-internals mailing list
> [email protected]
> https://lists.mozilla.org/listinfo/dev-tech-js-engine-internals
>
_______________________________________________
dev-tech-js-engine-internals mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-internals

Reply via email to