Reputation: 1487
I have an ArrayList
with 40,000 separate objects that can be drawn to the screen. Right now I have to iterate through all of them, and perform a calculation if they are showing on the screen, before I draw them with a Graphics2D
object.
for (GameObject object : gameObjects) {
if (insideScreenView(object)) {
object.draw(g2d);
}
}
This doesn't take too long, but it does take about 2-5 ms. Only about 100 of these objects are showing on the screen at any given time. Meaning that I am running 39,900 iterations that aren't necessary. Is there a better way to do this, given that I know most iterations don't have to happen.
Edit:
Objects are chosen to be on screen based on if an object's bounding rectangle intersects the screen via Rectangle
's intersects()
method.
Upvotes: 0
Views: 128
Reputation: 2243
Instead of iterating ALL the game objects, you should iterate only the viewable objects
.
So, how to do that?
->> METHOD 1 (slow, but simple) <<-
First, separate your game logic in 2 pieces: updateView()
, and draw()
.
updateView():
Here, you calculate
what objects are inside the screen, and add them to a simple List
(you can choose ArrayList
or LinkedList
, each one will have different performance impact, so, benchmark them!).
draw():
Here, you iterate over all the objects on the List
you created before on updateView
, and draw
them.
->> METHOD 2 (fast, but complex) <<-
The basic logic is somewhat like Method 1: you have the viewable objects inside a List, and draw them on draw()
method. But the difference between these methods is that, on this method, instead of each tick verify what objects are viewable, you check when the objects move
.
Depending on how your Game Objects are managed, Method 1 can be faster
(if your Game Objects are moving every time, like particles
), but for general purposes, this method is faster
.
So, inside Game Object, you add a boolean called addedToViewList
. This boolean indicates whether the object is added to the viewable objects list
, so we don't need to use list.contains(object)
and iterate over it. Then, every tick, you check if the object is already on the list. If it is, you check if he is viewable or not: if not, you remove
him from list. If he wasn't on the list, but he is viewable, then you add
him to list.
Example:
public void onMove() {
if (addedToViewList && !insideScreenView()) {
this.addedToViewList = false;
(view list).remove(this);
}
else if (!addedToViewList && insideScreenView()) {
this.addedToViewList = true;
(view list).add(this);
}
}
Hope I helped you. See ya!
Upvotes: 1