# Drawing textures off screen optimization required?

I recently started using LibGDX and I am wondering if I have to optimize my code when drawing textures/sprites off-screen, just like I used to do with XNA.

My biggest concern here is specifically for the TiledMapRenderer.render() method, which draws a tiled map, imported from the Tiled map editor software.

I don't know how reliable this test I tried was (I just used the Sprite and SpriteBatch class here), but here it is:

// Doesn't cause frame drop
spriteBatch.begin();
for (int i = 0; i < 50000; i++) {
mySprite.setPosition(i, i); // most of times this is off-screen
mySprite.draw(spriteBatch);
}
spriteBatch.end()

// Less than 1 frame per second
spriteBatch.begin();
for (int i = 0; i < 50000; i++) {
mySprite.setPosition(0, 0); // always inside the screen view
mySprite.draw(spriteBatch);
}
spriteBatch.end();


So, from what I observe, I assume that anything drawn outside of the screen with LibGDX is not being drawn, to improve performance. Is this the case ? If so, in what degree should I be abusing this feature ?

Is LibGDX just checking a couple of logical conditions with the camera/viewport I am using and the u,v coordinates I am trying to draw the texture to and determines if this texture should or should not be drawn ? Or is it a process that takes requires lot of resources from the system ? Keep in mind that I mostly care about the android devices.

Should I be worried about this at all ? Again, TiledMapRenderer.render() is my biggest concern here, but I would also like to know if there is an optimization with drawing textures off-screen in general as well.

## 1 Answer

Yes, libGDX does optimize in that area, but that is irrelevant to the code you've written here. In your first part where you drew off-screen, you went and drew off to position 50000 that would be taxing to the computer, but the fact of the matter is that your Gdx.graphics.getWidth() / Gdx.graphics.getHeight() is unlikely to be ever 50000 unless you are trying to make a game that only works on a very large screen. Therefore it is impossible for libGDX to draw after a certain point, cutting off the drawing once it leaves the viewport size. In the second part, you are drawing the same image 50000 times before continuing to the next frame, naturally that would slow the game by a lot. The difference between the two is that one is impossible after a certain point and stops, decreasing the workload to be like 2500 times the amount; whereas the other is possible and the workload remains the same.

So yes, libGDX does optimize, but the code you've written here doesn't test for that correctly. Naturally you should always try to avoid abusing the gift libGDX has given us, but at the same time you needn't fret over it ;)