Brush and pen disposing

Have a doubt about working with brushes and pens.

I'm working on a custom control that inherits from Panel and draw a colorfull desing background on it. Shall i create brushes and pens once and keep them in class scope variables, then overrides Dispose to release those resources. Or shall i create brushes and pens, and dispose them, every time control paint itself in the paint method.

What's more expensive brushes creation and destruction or keeping those resources allocated during control lifetime

Thanks in advance.



Answer this question

Brush and pen disposing

  • capriono

    Well, consider how much drawing you are doing. If its only 5 or 6 lines without a lot of math, then its just fine to create and destroy as you paint. If you need to do a considerable amount of work, you want to get as much pre-processing and pre-loading of the objects you will use. Its even cheaper to change these objects as you run instead of creating new ones. So if you know that you'll need 5 pens, but you use them 10 different ways during your paint code, changing the 5 pens 10 times each (50 times), is cheaper than creating pens 50 times and setting all the appropriate properties.

    It is good practice to get as much done as possible before you draw, and hold as much of it as you can in memory so you don't have to create and destroy objects. Remember there is quite a bit of code behind the objects you create and destroy, so creating takes time, and destroying takes time (if explicity destroyed, if you leave them open, you may have memory issues that look like a memory leak, but are just a lagging garbage man).



  • Brush and pen disposing