Say I want to add a value to an array, but it doesn’t matter where, as long as the current item at that index is null. This null could be anywhere in the array, at random locations. I just want to have my value
somewhere in my array. Should I iterate over it like this:
for (int i = 0; i < 64; i++) {
if (items[i] == null) {
items[i] = obj;
return;
}
This way it may have to iterate over a lot of elements before it finds a null spot. Would it be faster to use another type, i.e. ArrayList ?
This is for a game, so performance is very crusial, and this is done maybe 300 times per second (also accessing, and deleting items). So for a game, what should I use best to store items, to iterate over ?
One way I have used in the past is to use an array and a Queue. Any time you add a object to the array you first check your queue to see if you have any empty slots. Anytime you destroy a object you set the array slot to null and add the index to the queue so you can quickly pull it out later. During my tests this was faster than a List because you only resize the array if you make it bigger.
code wise