I have an application that does a lot of drawing, let’s pretend it’s a Viso-like application. It has objects that have multiple sub-objects that are drawn, things can be connected, resized etc. Currently when I call paint on a particular sub-object or object, I do the following:
using(var pen = new Pen(this.ForeColor))
{
// Paint for this object.
}
I’ve read conflicting answers that this should be done for an application that is constantly drawing the same thing (maybe just resized, moved etc). Should I store the Pen/Brush with the object and then dispose them all when the application is disposed of, or are they efficient enough to be created/disposed for each paint call (remembering that this is a pretty graphics intense application).
EDIT: There are already two answers that have conflicting answers and this is where I’m not sure to make the switch. Does anyone have any stats on the differences?
You could of course use the Pens and Brushes classes that provide you with objects that are already created by the runtime.
For example, if you want one of the standard colour Pens, you can do this:
Likewise you can do the same with Brushes, if you just want standard solid brush colours:
Using these, you don’t need to worry about cleaning them up, disposing it or otherwise.
If you want different colours that you create yourself, for example with a different alpha component, or a gradient brush perhaps, then you still need to create these yourself and clean them up appropriately.
EDIT:
To create and dispose of an array of 100,000 new pens took approximately half a second on my ancient old XP machine, running a test app in Debug mode.
That equates to approximately 5 microseconds per pen. Only you can decide if that is fast enough for you. I would hazard a guess that this time may be largely insignificant with regard to the rest of your operations.