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.