2
function f() {
   // some code.. then:
   var bloburl = URL.createObjectURL(canvasToBlobOutput)
   // I could would do the following line, but assume I don't
   // imgElement.src = bloburl;
   // will this leak memory?
 }

If I would uncomment the imgElement.src line, I understand that the img element would "hook" the blob object in memory. But if we would run the function like it is (without this line), I dont see a reason why the bloburl could not be GCed? as we have no reference to it after the function.

Tony Hinkle
  • 4,706
  • 7
  • 23
  • 35
user3599803
  • 6,435
  • 17
  • 69
  • 130
  • MDN: The [`URL.createObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) static method creates a DOMString containing an URL representing the object given in parameter. **The URL lifetime is tied to the document in the window on which it was created.** Browsers will release these automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so. – Andreas Jun 14 '16 at 13:47
  • read that, obviously everything is released when the window/document is unloaded.. I just don't understand why the object is kept in memory even when there's no reference to it, so as I understand, my example would leak memory – user3599803 Jun 14 '16 at 13:50

1 Answers1

3

The string cannot act as GC-edge to the blob because strings can be manipulated. Therefore the blob must be put into an internal registry that prevents it from being GCed so it can be loaded from the generated blob URI.

Imagine there being a hidden Map instance and URL.createObjectURL implemented as:

function createObjectURL(blob) {
   let uri = generateRandomURI()
   window._hiddenMap.set(uri, blob)
   return uri
}

That way the internal map can be checked when someone tries to load that URI. But that map also has to hold the blob alive because the URI might be the only remaining reference to that blob.

To remove that gc-edge you have to revoke the URI.

the8472
  • 40,999
  • 5
  • 70
  • 122