سؤال

ECMAScript 6 introduces weak maps, which are implemented in Node.JS v0.11.3 with the flag --harmony.

Consider the following piece of code.

var weakMap = WeakMap();
var temp = {};
weakMap.set(temp, 'Save me!');
temp = {};

When the last line is executed, the string 'Save me!' is ready for garbage collection. Can it be demonstrated with code that the string no longer has a chain of strong references leading to it from the current scope?

I know weak maps do not have iteration or a size property similar to maps. Does it mean that there is no way of knowing a posteriori that a given object is no longer accessible from the weak map?

هل كانت مفيدة؟

المحلول

You can't, because it doesn't make sense to do so. There's just no good way to ask if something is reachable if you can't reach it. If there were a function

isStronglyReachable(foo)

then how would you pass it an unreachable foo? There's no way to pass it a weak reference to foo, and if you pass foo directly, then you know it's strongly reachable because you just used a strong reference to it (and binding it to a parameter creates another strong reference or two). You could try something of the form

weakmap.isValueStronglyReachable(key)

but then you'd need a strong reference to the key, which would make the value strongly reachable. Even if you tried something of the form

weakmap.getArrayOfUnreachableKeys()

(which would make the returned objects reachable through the returned array), the runtime would have to run a full GC pass to figure out which values are unreachable - and if it's doing a GC pass, why wouldn't it just delete the entries for unreachable keys?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top