Use cases for WeakMap

Hudson, Rick rick.hudson at
Mon May 16 14:46:07 PDT 2011

The other hack is to make the hash value itself opaque as I believe weak maps could. That way you can use the address as the hash at the cost of having to lazily rehash after a GC. Typically the Cheney scan of a hash table would randomly reordered objects in memory and this hurt memory performance. The optimization was to delayed scanning hash tables until the end of the Cheney scan so linked objects would have already been placed in memory order.

This is all a bit off topic but performance does matter and folks seem to be underestimating the wealth of community knowledge that exists in this area.

- Rick

-----Original Message-----
From: es-discuss-bounces at [mailto:es-discuss-bounces at] On Behalf Of Allen Wirfs-Brock
Sent: Monday, May 16, 2011 4:47 PM
To: Oliver Hunt
Cc: Andreas Gal; Brendan Eich; es-discuss
Subject: Re: Use cases for WeakMap

On May 16, 2011, at 11:37 AM, Oliver Hunt wrote:

> The same logic applies to object hashcodes -- an object must always produce the same hashcode which means it will need to store it -- having a secondary map doesn't help you, because that map will itself require a hascode.  However making every object always have space to store a hashcode is wasteful of memory, so essentially some form of "private name" must be used.  I think i saw someone (Erik?) say that this is what v8 does.

Old trick that works well when you have a copying collector:

Hashes are initially stored, on first demand,  in a side-table that is a hash table keyed by the current address of an object.  When an object is moved by the collector it checks to see if the object has a hashcode in the side table. If so, it adds a slot at the new location of the object and stores the hashcode in that slot.  It also removes the entry from the side table.

This requires 2 bits in the object header to represent the following states:
Object's hash has not been accessed so it is unassigned.
Object's hash is in the side-table.
Object's hash is in the hash slot.

If you can generate a suitable hash value based upon the object's current address you don't actually need the side-table.

If you want to have a readonly header that is ROM-able you can either always assign a hash slot to such objects or you can always  keep their hash in the side-table.


es-discuss mailing list
es-discuss at

More information about the es-discuss mailing list