is calling libgdx SpriteBatch begin and end method multiple times expensive?

Pogs D Best picture Pogs D Best · Jun 19, 2013 · Viewed 8.2k times · Source

Are the libgdx SpriteBatch begin and end methods expensive for the processor or make the performance slow if I call them multiple times?

For example:

public void render(float delta) {
GL10 gl = Gdx.gl10;
gl.glClearColor(0, 0, 0, 0);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

batch.begin();
//draw something
batch.end();
//do something before draw the others
batch.begin();
//draw others
batch.end();
//update
//controls
}

On the code above I just only call 2 times begin and end. But I want to do it 4 or 5 times....will this slow things down?

Answer

Lestat picture Lestat · Jun 19, 2013

It is not expensive. Do not worry. Just remember you don't have to, if you are using different textures you don't have to call begin and end for each. it automatically switches the texture for the region you are drawing. Of course, this means you have to group the drawing calls of the regions.

This will explain it better, suppose we have an atlas with all the TextureRegions of Hero and Enemies, and another one with all the TextureRegions of Coins and Platforms:

//You only need to call batch.begin once:

batch.begin();
//then draw
//-Hero
//-Enemies
//(Automatic texture switching here)
//-Coins
//-Platforms
batch.end();

As a little plus, there is a special case: Usually you have a background that fills all the screen, totally opaque. So disabling blending for that draw definitely improves performance. So you batch once for it, and then again for the other regions, like this:

batch.disableBlending();
batch.begin();
//draw background
batch.end();

batch.enableBlending();
batch.begin();
//etc