StructList
StructListX<T> is a list type that holds the first X number of elements in stack before anything is allocated from heap.
StructList4<int> list = new StructList4<int>();
list.Add(5); // 1st: Allocated on stack
list.Add(2); // 2nd: .. stack
list.Add(3); // 3rd: .. stack
list.Add(8); // 4th: .. stack
list.Add(10); // 5th: Allocated in heap
.ToArray() creates array in one pass.
int[] array = list.ToArray();
int[] arrayReverse = list.ToReverseArray();
StructListSorter does in-place sorting without heap allocation.
StructList10<int> list = new StructList10<int>() { 5, 2, 3, 8 };
var sorter = new StructListSorter<StructList10<int>, int>(Comparer<int>.Default);
sorter.Sort(ref list);
StructListSorter can also do binary search. This requires that elements are sorted.
StructList10<int> list = new StructList10<int>() { 2, 5, 7, 8, 10 };
var sorter = new StructListSorter<StructList10<int>, int>(Comparer<int>.Default);
WriteLine(sorter.BinarySearch(ref list, 8)); //3
StructListX<T> implements IList<T>. When passing struct list to a method, it's recommended to use generics constraint for IList<T> to prevent boxing.
StructList10<int> list = new();
list.Add(1);
Process(ref list);
WriteLine(String.Join(", ", list.ToArray())); // 1, 10, 11, 12
public static void Process<List>(ref List list) where List : IList<int>
{
list.Add(10);
list.Add(12);
list.Add(13);
}
.GetRef(ref list, index) returns 'ref' pointer to list element.
// Allocate list on stack
StructList1<int> list = new StructList1<int>() { 2, 5, 7, 8, 10 };
// Get pointer to element [0]
ref int pointer = ref StructList1<int>.GetRef(ref list, 0);
// Read from pointer
WriteLine(pointer); // 2
// Assign value '4' at pointer
pointer = 4;
// Read from list (value is changed)
WriteLine(list[0]); // 4