- Home /
Invoke repeating OR coroutine with WaitForSeconds?
Hi everyone! I'd like to ask a more "theorical" question, mainly regarding performance.
If I want something to be executed periodically (but not as frequently as Update() would do it), what is my best option available, performance-wise?
Is it this:
InvokeRepeating("DoSomething", 0.0f, TIME_BETWEEN_EXECUTIONS);
void DoSomething() {
Debug.Log("Hello Internet!");
}
... Or this?
StartCoroutine(DoSomething());
IEnumerator DoSomething() {
while (true) {
Debug.Log("Hello Internet!");
yield return new WaitForSeconds(TIME_BETWEEN_EXECUTIONS);
}
}
Thoughts?
Thank you for your time!
Answer by JedBeryll · Oct 04, 2016 at 09:05 AM
IEnumerator should be somewhat faster for the simple reason that Invoke uses a string name for finding the method which is slower than a specified call.
Interesting, I hadn't thought of that. However the IEnumerator one has:
A "new" clause, which always involves reserving and freeing memory.
$$anonymous$$ultiple calls to the WaitForSeconds() function, as opposed to the multiple calls done to DoSomething() in the other approach
The extra call to DoSomething() at the start (counted in for excretions and giggles, but this thing I'm implemented is pretty resource-intensive).
If you're worried about the new being called every time, you could always do this when the time is fixed:
StartCoroutine(DoSomething());
WaitForSeconds time= new WaitForSeconds(TI$$anonymous$$E_BETWEEN_EXECUTIONSf);
IEnumerator DoSomething() {
while (true) {
Debug.Log("Hello Internet!");
yield return time;
}
}
To be honest i'm not really worried about the "new" keyword, I used it many times and never really experienced a framerate drop because of it even when i do it 40 times / second. And you probably don't need to micromanage this so much because it's already as efficient as it can be. If you need to free up cpu, you probably need to look around in your own code.
However you have a third option: you can count down in Update which eli$$anonymous$$ates the WaitForSeconds but introduces an "if" and a subtraction. (again if you experience performance drop it's probably not because of the "if" and "-")