This is the eighth part of the Custom memory allocation series. For your convenience you can find other parts in the table of contents in Part 1 — Allocating object on a stack
Today we are going to revisit an Unsafe list example using .NET Core. Since I use x64 edition, I need to adjust a code using pointers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public void Add(T item) { _currentIndex++; unsafe { TypedReference reference = __makeref(item); long* itemAddress = (long*) (*(long*) *(long*) &reference - 8); for (long i = 1; i < _elementSize; ++i) { _storage[_currentIndex*_elementSize + i] = *itemAddress; itemAddress = itemAddress + 1; } reference = __makeref(_storage); _storage[_currentIndex*_elementSize] = *(long*) *(long*) &reference + _currentIndex*_elementSize*8 + 32; _elements[_currentIndex] = GetInternal(_currentIndex); } } |
Changes are rather simple — one just needs to replace integers with longs and multiply all the offsets by two.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Poco { public long Field1; public long Field2; public long Field3; public long Field4; public long Field5; public long Field6; public long Field7; public long Field8; public long Field9; public long Field10; public long Field11; public long Field12; public long Field13; public long Field14; public long Field15; public long Field16; } |
Here I just use long fields to make the code simpler. Of course one can detect the size of the object and work with integers as well.
Here are the results:
Unsafe list is still faster.