Calling createGraphics() many times causing memory leak

I have a sketch I’ve been working on, and I found that calling createGraphics() repeatedly causes memory to not be freed. Representative example:

var size = 600;

function setup() {
  createCanvas(size, size);
  stroke(0);
  strokeWeight(10);
}

function draw() {
  let pg = createGraphics(size, size);
  pg.rect(size/4, size/4, size/2, size/2);
  image(pg, 0, 0, 600, 600);
}

How can I delete the pg instance between draws?

I Javascript garbage collection takes care of releasing unused memory, but it can take a while. Garbage collection in simplest cases cleans objects that have no references any more, but there are other strategies too. For more information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management or https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec

You can try to set pg variable to null to make sure that there are no references to created graphics object, but in the end it’s up to garbage collection to free the memory. Most likely it depends on browser and their javascript implementation how, when and how it happens. After all that script creates 60 graphics objects in a second so some of them will be in the existence at the same time.

1 Like

I’ve noticed this in regular processing too. The temporary PImages would use the same var name and therefore shouldn’t need to use extra memory yet on every loop memory would go up constantly until memory leak error.

Java uses garbage collection too to clear unused memory. Variable is just a reference to object, that has memory allocated to it. Clearing variable or putting another object to it does not free the memory. It happens later in the background. If you consume memory faster than garbage collection can free it, you’ll run out of memory.

2 Likes

Helpful, thanks @SomeOne.