Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How this loop can be optimized?

Let’s say that this is loop class:

package net.boyernek.example.engine;

import java.awt.Graphics;
import java.util.LinkedList;

public class Loop {

    public LinkedList<Entity> entities = new LinkedList<Entity>();

    public void tick() {

        for (int i = 0; i < entities.size(); i++) {

            entities.get(i).tick();
        }
    }

    public void render(Graphics g) {

        for (int i = 0; i < entities.size(); i++) {

            entities.get(i).render(g);
        }
    }
}

And let’s say that this is entity class:

package net.boyernek.example.engine;
    
    import java.awt.Graphics;
    import java.awt.Rectangle;
    
    public abstract class Entity {
    
        public float x, y, velX, velY;
        public int width, height;
        public ID id;
        
        public GameObject(float x, float y, ID id) {
            this.x = x;
            this.y = y;
            this.id = id;
        }
        
        public abstract void tick();
        
        public abstract void render(Graphics g);
        
        public abstract Rectangle hitbox();
    }

So I want to create open-world map. I create for example 50k block entities and game runs like 30 fps. How can I optimize this loop so my game can handle hundreds of thousands of entities which are textured, have their own collision checks and for alive entities even simple AI implemented. I know about thing called "frustum culling", but I have no idea how to implement it here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Replace LinkedList with ArrayList or Array (if you don’t need to resize the collection). This has been discussed here

Other optimizations like loop unrolling will be automatically done by the JVM

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading