Use cases for WeakMap

Allen Wirfs-Brock allen at
Mon May 16 13:46:51 PDT 2011

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.


More information about the es-discuss mailing list