Performance: Stopping coroutines
This affects runtime responsiveness and CPU usage during gameplay by controlling how coroutines consume resources.
Coroutine myCoroutine = StartCoroutine(MyCoroutine()); // Later StopCoroutine(myCoroutine);
StartCoroutine(MyCoroutine());
// Later, forgetting to stop it
// Coroutine keeps running and consuming CPU| Pattern | CPU Usage | Frame Impact | Reliability | Verdict |
|---|---|---|---|---|
| Not stopping coroutines | High (runs every frame) | Increases frame time | N/A | [X] Bad |
| Stopping by string method name | Medium (string lookup overhead) | Moderate frame impact | Error-prone | [!] OK |
| Stopping by Coroutine reference | Low (direct stop) | Minimal frame impact | Reliable | [OK] Good |
| StopAllCoroutines indiscriminately | Medium (may stop needed coroutines) | Unpredictable frame impact | Risky | [!] OK |
IEnumerator ExampleCoroutine() {
Debug.Log("Start");
yield return new WaitForSeconds(2);
Debug.Log("End");
}
void Start() {
Coroutine c = StartCoroutine(ExampleCoroutine());
StopCoroutine(c);
Debug.Log("Stopped");
}IEnumerator MyCoroutine() {
yield return new WaitForSeconds(1);
Debug.Log("Done");
}
void Start() {
StartCoroutine(MyCoroutine());
StopCoroutine("MyCoroutine");
}Pass the test and this pattern moves unknown