Information Technology Reference
In-Depth Information
// Sample one
protected override void OnPaint( PaintEventArgs e)
{
// Bad. Created the same font every paint event.
using ( Font MyFont = new Font ( "Arial" , 10.0f ))
{
e.Graphics.DrawString( DateTime .Now.ToString(),
MyFont, Brushes .Black, new PointF ( 0 , 0 ));
}
base .OnPaint(e);
}
OnPaint() gets called frequently. Every time it gets called, you create
another Font object that contains the exact same settings. The Garbage
Collector needs to clean those up for you every time. That's incredibly
inefficient.
Instead, promote the Font object from a local variable to a member vari-
able. Reuse the same font each time you paint the window:
private readonly Font myFont =
new Font ( "Arial" , 10.0f );
protected override void OnPaint( PaintEventArgs e)
{
e.Graphics.DrawString( DateTime .Now.ToString(),
myFont, Brushes .Black, new PointF ( 0 , 0 ));
base .OnPaint(e);
}
Yo u r p r o g r a m n o l o n g e r c r e a t e s g a r b a g e w i t h e v e r y p a i n t e v e n t . T h e
Garbage Collector does less work. Your program runs just a little faster.
When you elevate a local variable, such as a font, that implements
IDisposable to a member variable, you need to implement IDisposable in
your class. Item 18 explains how to properly do just that.
Yo u s h o u l d p r o m o t e l o c a l v a r i a b l e s t o m e m b e r v a r i a b l e s w h e n t h e y a r e
reference types (value types don't matter), and they will be used in routines
that are called very frequently. The font in the paint routine makes an
excellent example. Only local variables in routines that are frequently
accessed are good candidates. Infrequently called routines are not. You're
trying to avoid creating the same objects repeatedly, not turn every local
variable into a member variable.
 
Search WWH ::




Custom Search