why call bufferStrategy.getDrawGraphics() every gameloop cycle?

i’ve noticed that most game loop look something like this:
public static void Main(String[] Args)
{
while(true)
{
g = (Graphics2D) bufferStrategy.getDrawGraphics();
//do drawing
}
}
while i prefer:
public static void Main(String[] Args)
{
g = (Graphics2D) bufferStrategy.getDrawGraphics();
while(true)
{
//do drawing
}
}
why is this wrong (i’m guessing it’s wrong because i haven’t seen any code like this)?

I just assume that BufferStrategy internally is based on some type of VolatileImage and if a VI gets unuseable that its graphics-object is unuseable too.
For sure BufferStrategy does some clever caching internally to not unesscesary create tons of graphics-objects :wink:

lg Clemens

When you call getDrawGraphics() you are getting the graphics context that will be drawn into.
When you set up a BufferStrategy with for example 2 buffers, you have two possible locations to draw into. The BufferStrategy handles all the blitting or flipping and each time it flips, a different context is used to draw into.

So you need to get the Graphics2D object that contains the current context to draw into.

At least that is my assumption. I’ve never seen an official reason for getting a new g each time, but I’ve never seen the question before either :slight_smile:

Always get the graphics object, paint and dispose. Each frame.

Reusing the graphics object doesn’t yield a speed increase and it can lead to unlimited memory consumption on the mac. Been there… done that. There is no need to repeat my mistakes :wink:

An optimisation like that (removing one cast and one get method) would only yield a speed increase if it would happen very often per frame. Keep in mind that passing a reference around is a very cheap operation. And don’t waste your time with things which won’t make a difference. Using a profiler clearly helps :slight_smile:

how come? it doesn’t make sense,that calling a method (that isn’t disposal related) fewer times can cause memory consumption…

Dunno really. Looks like it accumulates some kind of data until you dispose… since that never happend it eventually went throught the roof.

it’s a shame there isn’t a complete guide for this…
i always saw the calls to dispose on Graphics objects, but never understood why… well, thanks anyway :slight_smile: