1

First, what I really want behind this question is to know if it would be possible to implement a reliable SoftMap in Javascript.

Babel, or the Memoizee lib seems to provide polyfills for ES6 WeakMap/Set. I've tried to read the code but I'm not really sure to understand how it works.


Coming from a Java background, I understand what is a WeakMap (we have WeakHashMap for a long time, and even Weak/Soft/Phantom references for a long time).

The thing is, in Java, to implement a WeakHashMap we use low-level primitives provided by the JVM like WeakReference.

I don't really understand how a polyfill of WeakMap can be created without low-level reference primitives.

Can someone please explain to me, in an older browser we'd like to polyfill, how it would be possible to track for a map key, if some objects outside the map refers to that key?


Also something is unclear. In Java we have soft and weak references while in Javascript there's only weak map/set. After reading some stuff about WeakMap it is still not clear to me how the GC will decide to collect the map entry. If the key becomes unreachable, the GC:

  • WILL always collect the entry immediately
  • CAN always collect the entry immediately (but may do later if it does not require memory right now)

This is the distinction between Weak and Soft in Java, and it is not clear what behavior ES6 should implement.

Community
  • 1
  • 1
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
  • Please ask only one question per question. If you still need an answer on the second part, consider posting a new one. – Bergi Dec 17 '15 at 17:39
  • I don't think I even understand your second question. "becoming unreachable" always only means that the GC *can* collect the object, and says nothing about when or even whether. And this doesn't seem to have anything to do with weak maps? – Bergi Dec 17 '15 at 17:40
  • thanks for the duplicate link it will be useful :) – Sebastien Lorber Dec 17 '15 at 18:20
  • @Bergi the difference between WeakMap and SoftMap (if implemented as in Java) would mean that with SoftMap the entry will be GC only when the browser needs memory, while with WeakMap the GC will collect the entry as soon as the GC runs). Weak = collected more early. Soft = collected later (but maybe never if there is plenty of memory). SoftMap can be useful to implement in-memory caches and make full use of memory when there is a lot of available memory. – Sebastien Lorber Dec 17 '15 at 18:25
  • Sounds like a SoftMap does compare keys by value, not by identity; and does clear key-value pairs at will (when it needs to free memory). That's not what an ES6 WeakMap does, it will hold the value until the key becomes unreachable. – Bergi Dec 17 '15 at 18:31

0 Answers0