Information Technology Reference
In-Depth Information
The static property Brushes.Black used earlier illustrates another technique
that you should use to avoid repeatedly allocating similar objects. Create
static member variables for commonly used instances of the reference
types you need. Consider the black brush used earlier as an example. Every
time you need to draw something in your window using the color black,
you need a black brush. If you allocate a new one every time you draw any-
thing, you create and destroy a huge number of black brushes during the
course of a program. The first approach of creating a black brush as a
member of each of your types helps, but it doesn't go far enough. Pro-
grams might create dozens of windows and controls, and would create
dozens of black brushes. The .NET Framework designers anticipated this
and created a single black brush for you to reuse whenever you need it.
The Brushes class contains a number of static Brush objects, each with a
different common color. Internally, the Brushes class uses a lazy evalua-
tion algorithm to create only those brushes you request. A simplified
implementation looks like this:
private static Brush blackBrush;
public static Brush Black
{
get
{
if (blackBrush == null)
blackBrush = new SolidBrush ( Color .Black);
return blackBrush;
}
}
The first time you request a black brush, the Brushes class creates it. The
Brushes class keeps a reference to the single black brush and returns that
same handle whenever you request it again. The end result is that you cre-
ate one black brush and reuse it forever. Furthermore, if your application
does not need a particular resource—say, the lime green brush—it never
gets created. The framework provides a way to limit the objects created to
the minimum set you need to accomplish your goals. Copy that technique
in your programs.
Yo u ' v e l e a r n e d t w o t e c h n i q u e s t o m i n i m i z e t h e n u m b e r o f a l l o c a t i o n s y o u r
program performs as it goes about its business. You can promote often-
used local variables to member variables. You can provide a class that stores
singleton objects that represent common instances of a given type. The
 
Search WWH ::




Custom Search