when using a foreach loop in Unity I need to call this in the update method. So it's called once per frame...
I want to know, if it is better to check the count of the list before using the foreach loop or if it is redundant.
So I have
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();
}
Yes, it is equivalent. If the list is empty, the for-each cycle is not executed even once.
The question checks if the collection is null first before doing the for-each. Your link checks if the item in the collection is null.
Using the Code. The ForEach method of the List<T> (not IList<T> ) executes an operation for every object which is stored in the list. Normally it contains code to either read or modify every object which is in the list or to do something with list itself for every object.
Unless you need some specific logic if the list is empty, then the if statement is certainly redundant. In the foreach loop if there is no data - it simply does not perform the loop.
This is more or less of a concern for best practice rather than performance though. The impact is practically non-existent; however, I think its never a bad I idea to at least be aware of these type of things.
The performance difference is almost certainly negligible (but it never hurts to measure).
On the other hand, a pure foreach
will work for practically any collection, whereas using a for
loop or checking Count
(or Length
or Count()
) implicitly assumes that the collection is an IList
.
So, you have three options that are (probably) equally performant, but one is vastly more flexible than the others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With