Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting big blobs in javascript

I create huge blobs in the client which the user can download as files.

The following example is just to demonstrate the issue

var x= "sdfslkdfjklsdjiflskdflsdf" ; for(var i = 0; i<19;i++) x=x+x
var blob = new Blob([x,x,x,x,x,x,x,x,x,x,x,x,x], {
    type : "text/plain"
});

This will use up a lot of memory. When I'm done with the blob I would like to free up that memory. (I'm testing this in IE11 Edge)

Running this script twice will fail as no more memory can be allocated

I've already tried setting blob = null or using delete blob, nothing happens to the memory.

How to free up the memory?

like image 985
Calthabis Avatar asked Oct 30 '22 04:10

Calthabis


1 Answers

I think you are going to hit a wall here. Javascript is garbage-collected, which means the best you can do is "unset" variables to effectively mark them for garbage-collection, when the browser thinks it's time.

As charming as it might seem, setting to null will not free the allocated memory right away, but only remove a reference -- freeing memory only possibly later, when garbage-collection actually occurs (given that no other references to the involved object exist):

var blobA = new Blob(...);
var blobB = blobA;
blobA = null;
console.log(blobB); // Blob, the object still exists

Garbage collection is automatic, and there is no way to predict or detect when it happens from within Javascript. There is one way to manually trigger it, however:

window.location.reload();

That's correct, doing a full reload of the whole page will trigger garbage collection, which is effectively the only way to do it AFAIK. You might want to consider this when designing your application.

like image 143
John Weisz Avatar answered Nov 09 '22 05:11

John Weisz