Usage for weak-maps
Allen.Wirfs-Brock at microsoft.com
Fri Oct 29 09:29:14 PDT 2010
Weak maps are used to create an association (based upon object identity) between an object (the key) and some arbitrary information. They are necessary if you need to maintain such an association and you cannot modify the key object to directly record the association.
Without some sort of weak reference mechanism, the data structure needed to maintain such an associations is inherently leaky because the use of an object as a key creates a reference to the object that prevents its and its associated value from being garbage collected even if the key reference is becomes the sole reference.
There are many use cases for such object identify based maps. A basic one is a memoizing cache. Assume that there is some expensive computation (for example a database access) based upon some object and you want to memoize the result of the computation. A weak map can be used for that purpose without create a memory leak.
> -----Original Message-----
> From: es-discuss-bounces at mozilla.org [mailto:es-discuss-
> bounces at mozilla.org] On Behalf Of P T Withington
> Sent: Friday, October 29, 2010 8:34 AM
> To: Peter van der Zee
> Cc: es-discuss
> Subject: Re: Usage for weak-maps
> On 2010-10-29, at 04:50, Peter van der Zee wrote:
> > What's the use case for weak maps? What would you do with it that
> > currently impossible and why is the workaround (if any) problematic
> > enough to warrant a weak map implementation?
> Another use case was mentioned in the "New topic regarding Proxies:
> intercession for ===" thread. If you want to write a value type, the constructor
> needs to return the same object for identical parameters for === to work, which
> means it needs a table of all the objects it has ever made, but it doesn't need (or
> want) to hang on to objects that are no longer in use. [The alternative being
> discussed in the proxy thread is to be able to customize === to give the same
> illusion.] _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
More information about the es-discuss