sestoft / C5

C5 generic collection library for C#/.NET
http://www.itu.dk/research/c5/
MIT License
1.03k stars 181 forks source link

Memory safe enumerators for mobile development #37

Closed codingadventures closed 8 years ago

codingadventures commented 8 years ago

Hi,

I would love to use C5 for mobile game development. However, the usual way collections are iterated (through foreach statements and LINQ queries) is totally banned. The reason behind it is that creating an enumerator generates garbage.

In game development, and especially for mobile, this is absolutely to avoid. Generating too much garbage will eventually trigger garbage collection. Garbage collection is non-deterministic and in game development we want to be able to "predict" or "control" when it happens. Obviously if too much garbage is generated, GC will eventually kick in. If this occurs during a game loop, where each frame must be no longer than 16 ms, it will create stutters and it will bring down the frame rate resulting in an unpleasant experience.

At the moment the only workaround is using for loops instead of foreach's. There are cases (with dictionaries for example) in which using a for loop is not possible. Moreover, a for loop is very verbose. Having the option to use a foreach instead, it would be a great addition.

The Solution

For this reason I though of a reusable enumerator. I've extended some the C5 collections (ArrayList, SortedArray, WrappedArray, HashArrayList, HashDictionary, HashTable) . I added a default parameter for each constructor in each collection that accepts a MemorySafe type enum. E.g.:

var arrayList = new ArrayList<int>(MemoryType.Safe);

but it can be also:

var arrayList = new ArrayList<int>(); where the MemoryType is Default if no value is specified.

The enum has three options: Default, Safe and Strict. In Default mode the collection works as usual Anytime an enumerator is requested (through GetEnumerator() ) a new object is created. In Safe mode the same instance of an enumerator is returned unless the collection is iterated multiple times or accessed by multiple threads. In Strict mode the behaviour is the same as in Safe mode but an exception is raised in case of multiple enumeration or in case of multithread access to the collection. This is to guarantee that no garbage at all is generated.

I added more than 1300 unit test on top of the existing ones and all the 2705 unit tests are passing.

ondfisk commented 8 years ago

Thanks - accepted :)