Tutorial :Should a function that periodically returns bitmaps re-use them?


I have a function that returns a bitmap meant to be used as background in a panel, and occasionally I'd have to call it to create a new background based on parameters.

(Since there are two drawing functions for this panel (the background doesn't need to be changed as often as the foreground) it's not a matter of just drawing on the Paint event.)

So my question is: Is there a (more than symbolic) performance gain if I get the old background buffer as a paramenter and draw on it instead of creating a new bitmap every time the function is called?


Yes you gain quite a bit I would imagine.

For one, your memory constraints would be better bounded. If you're constantly creating Bitmaps, what's preventing your the client code from holding onto them and running you out of memory?

Allocation is usually one of the most expensive things in any large system. Reuse is definitely a good thing to have for objects that are expensive to create. You'll see less hiccups from Garbage Collection as well.

EDIT you can also consider maintaining your own pool of Bitmaps and not requiring the caller to pass in an existing one. Make sure you document that you own the Bitmaps and that the caller should treat them as read-only (can you wrap it in some immutable object?). That way you can create/dispose on your own time and not need anything from the client.


Yes, recreating a bitmap in code that runs while painting is usually far too expensive and slows down the painting too much. Keeping a copy of the bitmap solves the speed problem, at the expensive of needing more memory.

Note that the standard Control.BackgroundImage property is available for this, consider using it. You just need to add the code that updates that property (and calls Invalidate) when the conditions change that require a different background image. Drawing is automatic.

Secondary efficiency considerations are pre-scaling the bitmap to exactly fit the control's ClientSize, avoids having to rescale the bitmap at painting time. Big savings there, especially when the bitmap is large. But requires overriding the OnResize method so you can re-generate the scaled bitmap. When that slows down the painting too much while resizing the form then you need to wire the form's ResizeEnd event.

And creating the bitmap in the Format32bppPArgb pixel format, it draws about 10 times faster on most video adapters compared to any other format.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »