So in a game with various objects that perform various tasks, a naive approach would simply be to update the state of all of the existing items in the world every game update. This is what Minecraft does to handle furnaces, and similar items. A more efficient approach would be to schedule a task in the future, for example, when the next item will be smelted. Then only the current events need to be processed rather than all of them every update.
An implementation of this would be to have a sorted list, and every update, the start of the list is iterated and the items processed until a list item is reached that is scheduled to occur in a future update.
But what data structure would be most suitable?
- If I use a straight array, then only one allocation is used, but every time an element is inserted or removed, that will incur a shift of the remaining elements.
O(n)
complexity. The correct insertion point for an event scheduled to occur at an arbitrary time could be found via binary search withO(log n)
complexity. - If I use a linked list, then deleting the first few elements scheduled to occur in the current update would not entail traversing the entire list. But scheduling a new event would entail doing so, in order to find the correct insertion point.
What data structure would be most suitable for a constantly changing, ordered set like a scheduled events list? So far my only options have linear complexity for insertion and/or deletion. Is there an even better data structure that will have logarithmic or constant time complexity for that?