Multiple Canvases Are...Not Faster?

Thu, 11/23/2017 - 11:25

For the longest time I was under the impression that multiple HTML5 canvases would translate to faster performance.

Not sure where that idea might have come from

Regardless, the fact is that I built multiple canvases into Wes Mantooth as a core feature and yet the main example using multiple canvases was incredibly slow. I thought sure that it must be a memory leak. I followed several tutorials and installed benchmark and linter tools. I did learn a great deal from these resources that have helped the overall performance of Wes Mantooth and yet, the multiple canvas example was still slow as hell.

Anyways, I started looking at various JS libraries that used canvas and was noticing that they were running very fast with only one canvas...Imagine that.

So I refactored my code to allow for both single and multiple canvases.



balls performance multiple canvas


balls performance single canvas


The snapshot tests would suggest that in both cases there are paths to all the Ball nodes. Supposedly, no orphaned nodes require garbage collection but I noticed something unusual when looking at the memory allocation. When I add 20 balls on multiple canvases the program is regularly collecting garbage BUT when I add 60 balls using the same code...The program begins a run away memory leak.

20 Balls


60 Balls



Neither of these look like the single canvas memory profile. There is obviously a leak...But I just don't know why at this point. The following screenshot shows ideally what I should be seeing.

balls single canvas memory profile

Both methods use the exact same code aside from one creating multiple canvases. When the add_object hook is called a canvas is created, if necessary, and the game object is added to an array. With each loop the program loops all the game objects. The reference the canvas to draw to is based on the ID contained in the game Object. The profile would suggest that nodes are being added and never removed...but I don;t see why or where that would be happening.