Home

Awesome

UnsafeCollections

As this fork diverged too much from the original, it became its own repository.

This project contains various collections that perform no managed memory allocation. It alleviates GC (Garbage Collector) pressure useful for usecases such as Unity.

Project is targeted as a .Net 2.0 Standard library. Usable in Unity via dll.

Usage

The NativeCollections (under UnsafeCollections/Collections/Native/) are usable just like the matching collections in C# would. The API matches as much as possible with the C# API of the same collection. All of the NativeCollection objects are safe to pass as value.

You must instantiate the collections with any non-default constructor. After you are done using it, you again must call the Dispose function. The matching UnsafeCollection objects work similarly, but instead you must call Allocate and Free respectively.

Currently Implemented

Build

Use Preprocessor directive UNITY to build the project using the Unity memory allocators instead of the .Net ones.

The library is usable in both .Net and Unity.

Performance

Comparison is made for List between .Net List, UnsafeList and NativeList. This is done not only to show the difference between this and the .Net implementation, but also between the Native and Unsafe implementations.

List

Adding x items to a list, followed by a clear:

MethodMeanErrorStdDevGen 0Gen 1Gen 2Allocated
ListAdd196.98 ns0.253 ns0.236 ns----
NativeListAdd76.38 ns0.496 ns0.464 ns----
UnsafeListAdd58.59 ns0.293 ns0.274 ns----

Adding x items to a list where the list has to resize (followed by a clear):

MethodMeanErrorStdDevGen 0Gen 1Gen 2Allocated
ListAdd399.7 ns4.60 ns4.30 ns----
NativeListAdd161.2 ns0.13 ns0.12 ns----
UnsafeListAdd124.9 ns0.30 ns0.28 ns----

Grabbing the index of a "random" item in the list

MethodMeanErrorStdDevGen 0Gen 1Gen 2Allocated
ListIndexOf28.76 ns0.206 ns0.193 ns----
NativeListIndexOf23.69 ns0.038 ns0.036 ns----
UnsafeListIndexOf23.94 ns0.190 ns0.178 ns----

Because the difference in performance between Unsafe and Native is minor, only a comparison between .Net and Native will be made from this point onwards. Do note that the timings for the Unsafe collections are usually slightly lower.

Queue

Enqueue > Peek > Dequeue operations

MethodMeanErrorStdDev
QueueAddPeekRemove444.3 ns0.37 ns0.35 ns
NativeQueueAddPeekRemove194.4 ns1.47 ns1.23 ns
SPSCQueueAddPeekRemove219.2 ns0.19 ns0.17 ns

Sorted Set

SortedSet Add in reverse order (worst case)

MethodMeanErrorStdDev
SortedSetAdd1.118 μs0.0042 μs0.0040 μs
NativeSortedSetAdd1.964 μs0.0104 μs0.0098 μs

Dictionary

Dictionary Add followed by Remove

MethodMeanErrorStdDev
DictionaryAdd580.0 ns0.82 ns0.73 ns
NativeDictionaryAdd461.8 ns2.82 ns2.64 ns