Lets say I need to keep track of a million timer countdowns: A float variable which decrements by Time.deltaTime until it reaches zero, and then some function gets called. Which would theoretically perform better:
One timer being tracked in the Update call of a MonoBehaviour on a million game objects, or one game object looping through a million timers in one update call?
On the surface it seems like a silly question, because of course a million game objects is going to have a lot of data not-relevant to timer float variable. I’m imagining that unity wont put all update calls on the same thread, so maybe splitting up tasks similar to this across game objects would be better than having one gargantuan update that could chug and skip frames. Anyone with a strong understand of unity’s internals have any insight?
I would:
One timer, and a sorted array of float times for when events should expire
If the 0th element is < timer, remove from the array (or increase index), and trigger event
OK, so you’re talking about a lot of timers. So I would want to avoid looping over every entry and decrementing them, and especially don’t want to have a million calls to ‘Update’ just for a little timer. That’ll just take forever.
Instead how about we precalculate the end time for each entry, store as that, and then we just have to compare if the current time is greater than the end time to know if it’s done. Better, lets order them in the array/list in ascending order. This way if the first entry in the list is not done, then all following ones aren’t done either, so we can stop right there.
You can just forego the ITimer and manually call ‘Update’ on whatever Update interval you want.
The ‘StopWhenEmpty’ property is there because in my ITimer setup, completed timers are thrown out. Because this BulkTimer really is a bunch of timers grouped together, I’m allowing it to consider itself ‘complete’ once all timers have finished. But you might want to leave the empty timer in there for whatever reason so you can add more later. Again, you can ignore this if you want.