简体   繁体   中英

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM