Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 794
Question3r Avatar asked Aug 12 '17 14:08

Question3r


People also ask

Does foreach work on empty list?

Yes, it is equivalent. If the list is empty, the for-each cycle is not executed even once.

Does for each loop check for NULL?

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.

Does foreach work with lists?

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.


2 Answers

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.

like image 92
Chris Cruz Avatar answered Sep 19 '22 18:09

Chris Cruz


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.

like image 28
Rodrick Chapman Avatar answered Sep 21 '22 18:09

Rodrick Chapman