I’m coding in Java, but most languages would do just fine.
Right now, I have an implementation like this:
I have an array that stores objects from a class. The array’s length is 10,000.
This is for a little project I working on. Essentially, over time, any place in the array can be unused or have an object in it. Objects can be created or destroyed at any moment.
What I was trying to figure out was the best way to store and recall them to minimize time for two steps:
-
Creating an object. Cycling through the array until you find an open slot can be slow when lots of instances are near the front.
-
Drawing an object. I have to cycle through the array constantly, and, based on the existence of an instance, retrieve and display information regarding it.
My current system uses a list of the Objects, as well as a list of Booleans. When creating an object, I just cycle through till the first empty place in the array, then fill it, and to draw, I just go over the whole thing.
Granted, it isn’t slow enough to make the project impossible, but I’d still like to know the most efficient method.
The best way is not to do this. Use one of the Java collections. If you aren’t going to be adding or removing things very often, maybe use a
ArrayList. If you are, then use aLinkedList. And if you want to maintain a mapping to particular indices, you might consider e.g. aTreeMap. These are all iterable.