I was recently working with <canvas>
in JavaScript, and discovered the possibility to create a really bad "memory leak" (more like a memory explosion). When working with the canvas context, you have the ability to do context.save()
to add the drawing styles to the "state stack" and context.restore()
to remove it. (See the documentation for the rendering context on MDN.)
The problem occurs when you happen to continually save to the state stack without restoring. In Chrome v50 and Firefox v45 this seems to just take up more and more private memory, eventually crashing the browser tab. (Incidentally the JavaScript memory is unaffected in Chrome, so it's very hard to debug this with the profiler/timeline tools.)
My question: How can you clear out or delete the state stack for a canvas context? With a normal array, you would be able to check on the length
, trim it with splice
or simply reset is back to empty []
, but I haven't seen a way to do any of this with the state stack.
This is technically not a memory leak. A leak would be to allocate memory and loose the pointer to it so it could not be freed. In this case the pointer is tracked but the memory not released.
That is to be expected. Allocating memory without freeing it will accumulate allocated memory blocks.
The only way is to either restore all saved states, or to reset the context by setting some size to the canvas element (ie.
canvas.width = canvas.width
).It's also safe to call
restore()
more times thansave()
(in which case it just returns without doing anything) so you could in theory run it through a loop ofn
number of iterations. This latter would be more in the bad practice category though.But with that being said: if there is a mismatch in numbers of save and restore when it's suppose to be equal, usually indicates a problem somewhere else in the code. Working around the problem with a reset or running multiple restores in post probably will only contribute to cover up the actual problem.
Here's an example on how to track the count of save/restore calls -