[英]Coroutine with while loop vs update with if condition
我注意到每次我啟動協程時,都會產生一點點垃圾。 我只是想知道永遠循環協程是否是避免這種情況的有效方法。
而不是這個:
void Update()
{
if (condition)
{
StartCoroutine(Example());
}
}
IEnumerator Example()
{
if (coroutineRunning)
{
yield break;
}
coroutineRunning = true;
//Run code
yield return new WaitForSeconds(0.1f);
coroutineRunning = false;
yield return null;
}
我可以使用這個:
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
while (true)
{
while (!condition)
{
yield return null;
}
//Run code
yield return new WaitForSeconds(0.1f);
}
}
我已經對此進行了測試,並且永遠循環協程沒有 GC 分配。 我想知道循環這樣的協程是否有任何缺點。
協程是與主線程並行的進程,如果它一直在運行,應該不會產生問題,相反,它會從主線程中移除一些工作並減輕它的負擔。 所以,是的,第二個代碼比第一個代碼更有效。 考慮到你肯定知道,處理代碼的性能非常重要,但如果出現性能問題,則應首先考慮其他方面。
如果您認為我的回答對您有所幫助,您可以將其標記為已接受並投贊成票。 我將非常感激:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.