I’m wondering if this code here:
private bool Started = true;
private IEnumerator Start()
{
while (Started)
{
yield return new WaitForEndOfFrame();
}
yield return false;
}
Compared to this code here:
private void Start() {
}
private void Update() {
}
What code here would be faster, or would they both be the same speed?
Unless you have hundreds of objects the speed isn’t really an issue. Are you seeing a significant performance problem in the profiler relating to one of these? If so, change it and see if it makes a difference.
However, if you’re not seeing a performance problem then use the one that is most convenient for your use case. Get your code working first then worry about speed when/if it’s an issue.
What do you mean by faster? They both run once per frame. Since you’re not doing anything in either, speed is not a factor.
The real difference between the two is when the code will run. You can see where Update and code right after a WaitForEndOfFrame run in this diagram: Unity - Manual: Order of execution for event functions
There is some small overhead to both coroutines and update functions. I think that’s what he’s asking about. but I agree, in this example it’s a non issue.
Gotcha, alright thanks. This is a brand new program I’m writing so I’m looking at minuscule performance differences mainly.
Don’t waste your time looking at miniscule stuff. Stuff like this will NEVER be a bottleneck. You’ll be bound by pixel fill almost certainly. Make your game, if it chugs, attach the profiler and find out why.
As for the timing, this is why the above choices won’t make a difference: they are all in the same main loop:
Here is some timing diagram help:
As you can see, Update() gets called, then all the yielding coroutines get called, one after the other. No magic here, just a CPU doing instructions one after the other.
@Kurt-Dekker I gotcha, thanks Kurt, it’s just that when you scale it up more and more you want to pick the one that’d be faster I guess or something.
There is one key difference though and that’s that the IEnumerator one can be asynchronous, so that’s the advantage I’m looking for and why i want to make sure it’s the same as using the Update() otherwise.
No, absolutely not if it’s a coroutine in Unity.
Coroutines in Unity are done on the same exact thread either before or after Update(), however you want to look at it.
They give the outward APPEARANCE of asynchronicity but they are completely and totally single-threaded.
In other words, there will NEVER be a time that a Unity coroutine runs “at the same time” as anything else. NEVER.
See above timing diagram. There is ONE thread running your scripts in Unity, unless you start doing funky Jobs or threading stuff, and there is zero call for that unless you have profiled and found an issue.
1 Like