-
-
Save rwaldron/963596 to your computer and use it in GitHub Desktop.
var k = {}, v, | |
w = new WeakMap(); | |
w.set( k, "value" ); | |
console.log( | |
w.get( k ) | |
); | |
// ...At some point the program no longer needs this | |
k = null; | |
// Calling w.has( k ) using the es-labs implementation will return a useful `undefined`, here: | |
// http://code.google.com/p/es-lab/source/browse/trunk/src/ses/WeakMap.js?r=491 | |
// The current FF6.x implementation throws an exception "value is not a non-null object" | |
if ( w.has( k ) ) { | |
console.log( | |
w.get( k ) | |
); | |
} |
Since the div
variable still is referenced to a dom element, even though it's not in the body anymore, it wouldn't get garbage collected.
@SlexAxton: WeakMap is not dangerous, because you'll "lose" entries for keys you've already lost, so how could you look them up again ever? If you expect strong refs then yeah, use Map, but try to construct a program where this matters. You can't, cuz you'd need to keep the key alive with a strong ref to tell that it was in the WeakMap.
@rwldrn: see above -- the key is still alive so div is kept alive too. If you set both key and div to null around line 14, and then force a GC, then you can't look in the table (you nulled key, no way to look up and no way to for-in over keys still there) but you can be sure that the div is gone too. Our WeakMap may have debug-only enumeration support to test this.
/be
@be got it. I tried to walk through that logic rather poorly, above. dherman implied that Map was being heavily considered as well. Is there a reason we'd ever want Map over WeakMap? And if not, why not just called WeakMap -> Map - and just have it behave nicely with GC? (and thanks for your patience)
It's a good q, we have considered adding only WeakMap to Harmony, and Map and Set are not yet in harmony:proposals. But WeakMaps cost noticeably more in some applications than Maps, and if you want strong refs and that cost matters, then you'll grow to hate Map=WeakMap. So we're considering Map (and Set, which is just Map with key only, no value).
/be
@BrendanEich So, that's exactly what I expected, except that I only saw one log line - because I didn't notice the tiny "2" on the end of the line (incidentally, I was also pulled over sitting in the back seat of my Jeep when posted that - my phone had buzzed alerting me of the first few comments and couldn't wait until I got home) In a nutshell: rush job b/w a good story.
@BrendanEich I just added another example, is this an accurate example of the GC behaviour?