Created
May 9, 2011 22:54
-
-
Save rwaldron/963596 to your computer and use it in GitHub Desktop.
Example of WeakMap usage. Run in Firefox Nightly (>6.x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ) | |
); | |
} |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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)