When and how often should i call Spritebatch.Begin and Spritebatch.End

So currently i only call SpriteBatch.Begin and .End once for both my UI and World Rendertarget and then i draw every sprite to the screen. But now that i’m implementing a scrollable inventory container i did some research, which made me discover Viewport and Scissor Testing (even though at this point i haven’t quite understood them). Consequently i was confronted with the ways others talked about their methods of drawing and now i’m not quite sure if i’m doing it the right way.

Do i have any downsides by only calling SpriteBatch.Begin und SpriteBatch.End once and is it benefiacial to minimize the calls?

Edit:


Just found this thread and it says to call them only once and to use Flush if you have to change a state.

For me, I’m only using spriteBatch.Start()/End() once. Anyway, the best method is writing your own sprite renderer.

I think the answer is, “Whatever works best for you and your game.”

For ultimate efficiency, a single call to Begin/End is the way to go. However, this isn’t always practical. Sometimes it just makes more logical sense for the way your code is structured to Begin/End new batches. Sometimes you need to render to a target in the middle of sprite rendering so you can pull off some effect. Sometimes you need to use a different shader for something on a middle layer.

There are a number of legitimate reasons why you might have more, or nested, calls to these methods. You probably don’t want to do one for every single sprite you render (they don’t call it a batch for nothing), but past that, do what makes sense for you.

It probably is worth while to consider the scope of your project and consider what the performance requirements are. While “best possible performance” is a noble goal and all, it’s rarely practical and often leads to a butt ton of work that the final product probably doesn’t require anyway.

Personally I’m a fan of “optimize when necessary, but consider my needs ahead of time”, but you gotta go with your own instincts :slight_smile:

2 Likes

In MonoGame, Single SpriteBatch.Begin()/End() only have performance increase when you don’t change texture between Begin and End calls. If you changes textures, one texture change generates a DrawCall to GPU, which is equivalent as one SpriteBatch.Begin()/End() per texture.