I’m looking for a data-structure, or combination of several, that can give me a behaviour that satisfies these conditions:
- O(n) Iteration (does not have to be in-order)
- O(1) Contains
- O(1) Get (by key, which is an int)
- O(1) Add
- O(1) Remove
The three solutions I’ve come up with is something like this, which both are just uses of the built in collections in .NET
-
Build my own hash set which exposes more of the internal storage to the outside world then the default
HashSet<T> in .NET -
Use an
Dictionary<int, T>, as the iteration does not have to be in-order, but this is a very high performance application and the garbage that gets generated by creating the enumerator each time I need to step through the collection worries me. The worrying about garbage is not one I “made up”, this is for a real time simulation and any garbage that could trigger a GC basically a non-option if it can be avoided. -
Use a combination of a
Dictionary<int, int>and aT[], basically store the key + index into the array in the dictionary, and store the elements in theT[].
There is a generic KeyedCollection that allows objects to be indexed by an int and a key. The key must be embeded in the value.
You can use a for(int i…) to iterate over it without an IEnumerable.