foreach loops

The foreach loop keyword is a bit of a controversial issue in Unity development circles. It turns out that a lot of foreach loops implemented in Unity C# code will incur unnecessary heap memory allocations during these calls, as they allocate an Enumerator object as a class on the heap, instead of a struct on the stack. It all depends on the given collection's implementation of the GetEnumerator() method.

Note that it is safe to use foreach loops on typical arrays. The Mono compiler secretly converts foreach over arrays into simple for loops.

Since Unity 2018.1, Unity uses an upgraded Mono runtime (4.0.30319) and some compiler fixes many of the previous issues with foreach. As a consequence, foreach is no more a big issue in the general case. Yet, foreach still has a bad reputation among developers. The fact that sometimes they can actually be problematic makes everything more complicated. As usual, there is only one way to be sure: use the Profiler and check whether foreach is actually creating problems in your specific situation.

In any case, even in the worst scenario—that is, your foreach loop is actually doing heap allocations—the cost is fairly negligible, as the heap allocation cost does not scale with the number of iterations. Only one Enumerator object is allocated and reused over and over again, which only costs a handful of bytes of memory overall. So, unless our foreach loops are being invoked for every update (which is typically dangerous in, and of, itself), the costs will be mostly negligible on small projects. The time taken to convert everything into a for loop may not be worth it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.77.71