Libgdx lagging

I have a created a sprite ArrayList that holds ‘enemy’ sprites like so:


ArrayList<Sprite> enemies = new ArrayList<Sprite>();

I have ran into a problem while rendering these sprites. I have a for loop looping through the array of sprites and drawing each one onto the screen, but the game lags very badly. This is the code I have:


render(){
    batch.begin();
        for(int i = 0; i < enemies.toArray().length; i++){
            enemies[i].draw(batch);
        }
    batch.end();
}

I can’t do this without the for loop, so I can’t figure what else I can do.

It’s probably not the problem, but why on earth would you [icode]enemys.toArray().lengh[/icode] when you can [icode]enemys.size()[/icode]? Also I’m assuming you meant to spell “length.”

Note that enemies is spelled with an i ;D
Anyways, this isn’t nearly enough code to determine why you’re lagging. Post your code files or the render method at least.

Post what else is in your render method, or if that’s all, what’s in your enemy draw method?

unless there are like 60k enemies or they are very big this shouldnt produce lagging by itself

also do you mean stuttering or a low stable framerate ?

What’s in the enemy.draw() method?

It sounds like you are creating something big in there, like a texture.

Wait a minute

enemies[i].draw(batch);

If enemies is really an ArrayList you wouldn’t be able to index it like this. You’d need to use

enemies.get(i).draw(batch);

Are you converting enemies to a bare array at some point? If you were doing that in each loop iteration I could see that being very slow.

enemies.toArray() might be a very slow operation, depending on the size of the list. Since you repeat it every iteration of the loop, it might add up. Just do enemies.size()

toArray() is creating a new array every draw frame, and will cause a lot of GC

Yeah to get an idea: if you run the game at 120 FPS and you have 100 entities then every second you will generate 120 x 100 = 12.000 arrays of 100 items each. And this gets worse rapidly; if you have 1000 entities then you will generate 120.000 arrays per second of 1000 items each. Definitely fix this, and this could well be the source of your “lag”.

definitely.
I was kinda hoping that this wasnt your real code anyway, the misspelling of length kinda meant that this is not copy paste