Is URL.createObjectURL() a thin wrapper around a Blob, or does it hold its own copy of the buffer?

The URL.createObjectURL() function allows you to create a temporary URL from a Blob. I am aware that this function can leak memory (until the page is unloaded), so that it is often important to call the corresponding revokeObjectURL() function to free the memory, especially if you’re calling it in a loop. My question is not about such leaks, but instead about the memory overheads to createObjectURL() and the implications for when to call revokeObjectURL().

Most image Blobs would hold compressed data, which the browser of course needs to decompress in order to show the image. Does createObjectURL() create a thin wrapper around the Blob? Or does it decompress the image and then stores the full bitmap data until revokeObjectURL() is called? Or perhaps it makes its own immutable copy of the data so that changes to the Blob’s data don’t affect it? (Blobs are immutable so there’d be no reason to make a copy.)

In my case I’ll still be holding the Blob in memory, and so if createObjectURL() only makes a thin wrapper then I could keep the object URL in case I need to use it more than once. But if the overhead is high because it owns a large block of memory then I’d want to revoke it immediately after it’s used.

  • createObjectURL() isn’t only used for image data, so it can’t use image compression.

    – 

  • @Barmar I did have that thought, but Blobs/Files do have a mime type, so it could perhaps be possible to decompress it at the time of calling createObjectURL(). However even if it doesn’t decompress the data, it still might not be a thin wrapper, if it made its own copy of the buffer. I’ll add that possibility to the question.

    – 

  • There’s no mention of compression in the specification. I would expect the image to be compressed as part of creating the original PNG, JPEG, etc. data, it would be redundant to compress again when converting to a URL.

    – 

  • The MIME type is used to create the Content-type header when retrieving from the URL.

    – 

  • Oh, I see that Blobs are immutable, so createObjectURL() wouldn’t need to copy for that reason. And I had been wondering if createObjectURL() decompressed the data so that the browser could just immediately display it. But thinking more, that does seem unlikely, as all other image display methods would need to handle decompressing the data. So I don’t currently have any plausible reason for why createObjectURL() wouldn’t be a thin wrapper, but it would still be good to have it confirmed.

    – 




Leave a Comment