jackxiao / jslibs

Automatically exported from code.google.com/p/jslibs
0 stars 0 forks source link

GCHash (A Garbage Collectable Hash) #89

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
An implementation of a HashTable (object/map) where the items inside of it
can be garbage collected if not referenced by things outside the GCHash
would be useful.

Sometimes there are special cases such as special caches which store an
object so you know where to access it if it still exists, but don't want it
to sit around in memory if the cache is the only thing that is referencing it.
Likewise, take a namespace system based on objects. If no-one is using the
functions in those objects, then we don't really want to keep the objects
around do we? But at the same time we don't want to end up creating
duplicate objects for the same namespace.

I actually found a way to do this kind of thing in Ruby, so it would be
nice to have a simple way to do this in JavaScript as well. This kind of
thing I might actually make use of in core MonkeyScript to keep it efficient.

Original issue reported on code.google.com by nadir.se...@gmail.com on 18 Mar 2009 at 7:36

GoogleCodeExporter commented 9 years ago

Original comment by sou...@gmail.com on 6 Apr 2009 at 10:02

GoogleCodeExporter commented 9 years ago
I have implemented the following functions in jsstd: ObjectToId(obj) and
IdToObject(id) Where id is an integer.
If you try to get the object from the id and if the object has been GCed, 
IdToObject
returns undefined.
I think these tools are enough to create the system you described.

Original comment by sou...@gmail.com on 6 Apr 2009 at 9:30

GoogleCodeExporter commented 9 years ago
Sounds good. The only think I can think of, would be the issue of having a pile 
of
key/id pairs sitting around inside of the hash.
Is there any sort of GC Hook that can be made available with a fn call. So a 
GCHash
could register something like:
function GCHash()
  var hash = {};
  OnGC(function() {
    for ( let key in hash ) {
      if ( !IdToObject(hash[key]) ) delete hash[key];
    }
  });
}

And thus on a normal GC routine would go and delete dead keys.

Original comment by nadir.se...@gmail.com on 6 Apr 2009 at 10:20