Caching a Graphics object

G

Guest

Someone suggested that calling Control.CreateGraphics() is expensive and thus
it might be a good idea to cache the returned Graphics object. Is this true?

Back in the unmanaged world I remember something like there were only 5 DC's
to work with within your application so if objects attempted to cache their
DC's or if you had a leak your application would quickly freeze. I assume
the same sort of thing applies with the Graphics object unless it's a layer
above the DC. But if it's a layer above the DC I would not expect creating
one to be an expensive operation. Also, if it is expensive to create a
Graphics object and there is no harm in caching one I would have expected the
underlying framework (Windows / .NET) to have done the caching for me instead
of having each user of the framework implement their own caching mechanism.

(Also posted on the .NET drawing newsgroup)
 
H

Herfried K. Wagner [MVP]

nickdu said:
Someone suggested that calling Control.CreateGraphics() is expensive and
thus
it might be a good idea to cache the returned Graphics object. Is this
true?

No. 'Graphics' objects should not be cached because they will get invalid
if the underlying window handle gets recreated.
 
G

Guest

So they shouldn't be cached just because of recreating the window, or as I
mention below, does it hold onto a scarce resource (DC?)? I think someone
indicated a third party control library which caches the Graphics object and
re-caches (lets go of the current one and caches a new one) it each time the
window is resized. Someone else pointed me to:

http://msdn.microsoft.com/chats/transcripts/vstudio/vstudio_062602.aspx

which contains:

PeterG_MS
Q: Regarding overhead of passing objects to event handlers (such as
Graphics). There's more overhead than passing a pointer. The object must be
created and initialized. For every event, that seems like it would be a lot
of overhead. No?

PeterG_MS
A: Creating a Graphics object would have some significant overhead -- I
don't really know how much. But just passing a Graphics object has little
cost. So one way to improve performance would be a cache a Graphics object
and pass the same way on each event invocation, if possible.

I would rather stay away from caching the graphics object if possible.
Again my assumption is that if it's expensive to create the graphics object
and there is no harm in caching it the underlying framework (Windows / .NET)
would have cached it for us.
 
G

Guest

Hi Nickdu:
All graphics objects are created based on current graphics context of the
control so please drop the ideas of caching them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top