简体   繁体   English

Java for循环会减慢游戏速度

[英]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. 我在Java中有一个巨大的paint函数并且在许多for循环中运行时遇到了麻烦。 The objects that I want to paint are in ArrayList's so I have to use a for loop to draw them all. 我要绘制的对象在ArrayList中,所以我必须使用for循环将它们全部绘制。 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. 但是for循环将对所有对象运行:1.评价对象是否实际可见并应绘制2.绘制对象(如果可见)。

Thanks in advance and I hope you can help me :D 在此先感谢,希望您能帮到我: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:

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. 变慢的一种可能是,您在同一行中调用了3个相同的objects.get(loop)。 It is however possible that the JIT optimizes this away. 但是,JIT可能会对此进行优化。 Somebody who knows the JIT better than I could elaborate. 比我更精通JIT的人。

If the overhead of the for loop is really the culprit, the you can optimize it a little like this: 如果for循环的开销确实是罪魁祸首,则可以将其优化如下:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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