简体   繁体   中英

How to make loops more efficient?

I am having a problem with a basic code which displays some animated images in a 150x150 grid on the screen. (Note: Yes i know the images go off the edge of the screen but in the end i was planning to scale the images as required to fit the screen). However the program only runs at 2 FPS causing the animation to sometimes not work. My loop is currently as follows (in Java):

for (int i = 0; i < 22; i++) {
    for (int j = 0; j < 11; j++) {
        g2d.drawImage(getImage(texture_Ocean,l),i*64,j*64,i*64+64,j*64+64,0,0,64,64,this);
    }
}

And getImage:

public Image getImage(Image i, Long l) {
    BufferedImage b = (BufferedImage) i;
    int w = b.getWidth();
    if (b.getHeight() % w == 0) {
        int frames = b.getHeight()/w;
        int frame = Math.round((l%1000)/(1000/frames));
        System.out.println(frame);
        return b.getSubimage(0,(int) (w*frame) ,w, w);
    } else {
        return texture_error;
    }
}

My question is how can i make my program more efficient/run quicker? I know there has to be a way to do it as you see games such as prison architect and rimworld with words that are 300x300 and have hundreads of entities. And games such as TF2 which display thousands of polygons in 3D space. How?

The problem is that you are using the CPU (and through inefficient memory access methods as well) to do a job that the GPU is much better for.

You need to look at using something like a 2d graphics or games library or similar to get the sort of performance you are looking for.

The thing is, when developing games, you should care a lot with optimization. You can't simply call a paint method if you don't need it, and hope everything will be alright.

Besides that, you should try to look for a library dedicated to graphics (like OpenGL), since they can handle the optimization easily with the hardware.

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