Performance - check if the list is empty before using the foreach loop

when using foreach loop in Unity, I need to call this in the update method. Therefore, it is called once per frame ...

I want to know if it is better to check the counter before using the foreach loop or if it is redundant.

So, I have a

if (myList.Count > 0)
{
    foreach (Type type in myList)
    {
    }
}

and

    foreach (Type type in myList) // no need for a check before
    {
    }

I could also use

for (int i = 0; i < myList.Count; i++) // use a for loop instead
{
    myList[i].DoSomething();
}
+4
source share
2 answers

If you don’t need certain logic, if the list is empty, then the if statement is certainly redundant. In a foreach loop, if there is no data, it simply does not execute the loop.

, . ; , , , , .

+4

( ).

, foreach , for Count ( Length Count()) , IList.

, , () , , .

0

Source: https://habr.com/ru/post/1683579/


All Articles