Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created May 9, 2011 22:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwaldron/963596 to your computer and use it in GitHub Desktop.
Save rwaldron/963596 to your computer and use it in GitHub Desktop.
Example of WeakMap usage. Run in Firefox Nightly (>6.x)
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 )
);
}
@SlexAxton
Copy link

@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)

@BrendanEich
Copy link

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

@rwaldron
Copy link
Author

@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