Question

I have an implementation of the Sutherland–Hodgman algorithm, and so I need to return arrays frequently. I'm using Unity, so the answer needs to apply at least on the Mono runtime.

I'm wondering If it's best to return plain arrays, or if I could return as an IEnumerator, to reduce the time between garbage collections. So far I've been returning arrays, but I would really like to loose those calls to GC.Collect().

I guess the garbage collector would need to collect IEnumerators as well, and there is probably some overhead related as well?

Was it helpful?

Solution

When using generator co-routines (functions with many yield returns), no array is created or allocated. Everything is done in a streaming fashion. It is entirely possible to have infinite generators that work without getting an out of memory error:

public static IEnumerable<int> Odds(){
  for (int i = 1 ; ; i += 2)
    yield return i;
}

Therefore, if you frequently return big arrays only to be iterated and disposed immediately, the benefits will be huge, as the memory allocations will be much smaller. The garbage collector will be called less often and will have less work to do.

OTHER TIPS

First, just create your big array and keep it somewhere in memory. The rest of the application can retrieve a reference to that array and itterate through it.

The best way and fastest to itterate through an array is using for.

If you are using foreach, evertime (under water) a enumerator class is create, which will need to be cleaned up after it has done its duty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top