I have a class that contains two List of the same size that I need to convert to byte[] and copy them to another array.
Actually I use this code:
var lenght = MyObject.firstList[i].Count;
for (var i = 0; i < MyObject.firstList.Count; i++)
{
BitConverter.GetBytes(MyObject.firstList[i]).CopyTo(bytes, i * sizeof(float));
BitConverter.GetBytes(MyObject.secondList[i]).CopyTo(bytes, i * sizeof(float) + lenght * sizeof(float));
}
The problem of this code is that it always allocates a lot of memory causing the ** GC ** to intervene.
How can I optimize the code without making excessive memory allocations. Is there an optimal solution using unsafe or IntPtr or Span?
I tried to use this solution but the error appears
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory
PREMISE:
- I cant substitute List with a float[]