简体   繁体   中英

Java for loops slow down game

I am having some trouble where I have a huge paint function in java and i run many for loops. The objects that I want to paint are in ArrayList's so I have to use a for loop to draw them all. Is there any way to make this a lot faster? I have already integrated texture culling meaning that anything that is not needed, is not drawn. But the for loop runs for all objects to: 1. evaluate if the object is actually visible and should be drawn 2. draw the object if it is visible.

Thanks in advance and I hope you can help me :D

[edit] This is how i'd use it:

for(int loop = 0; loop < objects.size(); loop++)
{
    g2d.drawImage(objects.get(loop).image, objects.get(loop).x, objects.get(loop).y, null)
}

Obviously, i initialise my ArrayList somewhere else:

ArrayList<Block> objects = new ArrayList<Block>();

One possibility for slowness is that you are calling the same objects.get(loop) 3 times in the same line. It is however possible that the JIT optimizes this away. Somebody who knows the JIT better than I could elaborate.

If the overhead of the for loop is really the culprit, the you can optimize it a little like this:

int numBlocks = objects.size();
for(int loop = 0; loop < numBlocks; loop++)
{
    Block block = objects.get(loop);
    g2d.drawImage(block.image, block.x, block.y, null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM