2
\$\begingroup\$

I am refining my 2D game engine, and I want to look in to sorting sprite batches by texture (because I'm quite often using the same textures repeatedly).

However, I also want to retain a few 'layers' of depth (i.e. ground < buildings < units < GUI etc).

My question is, which of the following is the best approach (in terms of performance)?

  1. Create multiple SpriteBatches and Begin() and End() them in order; or...
  2. Create a single SpriteBatch and call Begin() and End() multiple times, once for each layer (in order)?
\$\endgroup\$
0

2 Answers 2

3
\$\begingroup\$

There is no reason to have multiple SpriteBatch objects unless you are using them as a "sprite buffer" (a list of sprites to be drawn when End is called) and filling multiple buffers up at the same time.

If you are going in and out of begin/end blocks, you can reuse the SpriteBatch object (there is no saved state between blocks).

There's no major effect on performance. But multiple SpriteBatch objects will use more memory.

As you probably already know, SpriteBatch (in XNA 4.0) only batches sprites together (improving performance) if two or more sprites share the same texture and are drawn sequentially and within the same begin/end block (and if Immediate mode is not set). It sounds like both of your methods will produce the same batches - and thus no performance difference.

\$\endgroup\$
0
\$\begingroup\$

You only need multiple SpriteBatches if you like to have other settings for the new layer. So using the same SpriteBatch twice or more is just fine.

You could also consider using only a single batch if everything is the same. Just sort your sprites into buckets and draw them at the right time within the batch.

\$\endgroup\$
5
  • \$\begingroup\$ When you say 'draw them at the right time within the batch', do you mean all sprites between a single Begin() and End()? Wouldn't the Textured SpriteSortMode override whatever order I draw them in? \$\endgroup\$
    – Motig
    Commented Jun 21, 2012 at 16:58
  • \$\begingroup\$ from msdn.microsoft.com/en-us/library/… - Deferred:"End will apply graphics device settings and draw all the sprites in one batch, in the same order calls to Draw were received" \$\endgroup\$
    – Marnix
    Commented Jun 21, 2012 at 19:04
  • \$\begingroup\$ But I'm using Texture sorting, not Deferred \$\endgroup\$
    – Motig
    Commented Jun 22, 2012 at 11:42
  • 1
    \$\begingroup\$ Why not just throw a timer over the draw call and see how much time each technique costs? \$\endgroup\$
    – Marnix
    Commented Jun 22, 2012 at 13:47
  • \$\begingroup\$ One reason that won't work very well is due to the way buffering commands to the GPU works. \$\endgroup\$ Commented Jun 22, 2012 at 14:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .