r/csharp • u/Drumsmasher17 • Jul 08 '17
Solved How Do I Stop This Case of GC Allocation?
I'm a student-tier game programmer, and have been using C# and Unity/Monobehaviour to make software for a couple of years now. I'm trying to do something new which involves working with bits & byte[] which I haven't needed to before. I'm familiar with the concept of pooling and using local variables to reduce GC Allocation. I should point out I'm very inexperienced with bitwise operations, and have no knowledge of how to use pointers!
The issue I'm having, is that I want to convert a couple of floats to byte arrays, several times a second - Initially I was using BitConverter.GetBytes(), but I found it was allocating 44B of memory for every use - This would add to the GC pile which get's collected when it reaches about 16MB, causing a spike of around 6ms, which is an unacceptable outlier for the normal game loop. Using C# and Mono's own GC, I don't have the ability to force GC on this specific bit of memory every frame (to my knowledge).
In my research, I found an example where someone had made a custom BitConverter class, and I'm wondering if there's a quick way of adding member variables to avoid the usage of "new byte[]", which I think is the cause of the GC allocation (I'm inexperienced with low-level stuff like this, so I may be wrong)
public static byte[] GetBytes(uint value)
{
return new byte[4] {
(byte)(value & 0xFF),
(byte)((value >> 8) & 0xFF),
(byte)((value >> 16) & 0xFF),
(byte)((value >> 24) & 0xFF) };
}
public static unsafe byte[] GetBytes(float value)
{
uint val = *((uint*)&value);
return GetBytes(val);
}I realise this is a really Noob-y question, but thank you in advance to anyone that can provide insight on this problem.
25
u/Daerkannon Jul 08 '17
I'm surprised no one has suggested this yet. The usual solution to this sort of problem is simply using pre-allocated buffers that get reused. In this case you change your method to something like:
Then simply recycle your byte buffers as needed.
3
u/[deleted] Jul 08 '17
I think you're looking for something like this. is the issue that you're returning the bytes? I've never had to do this sort of thing, but I imagine pinning and other things come into play if you need to return the bytes...
But if you're looking to return the values and allocation is the primary problem, you could probably just pass in a pre-allocated buffer and copy the bytes to that to prevent the allocation.
1
u/AngularBeginner Jul 08 '17
Simply return a struct instead of an array, e.g. (nasty code):
1
u/[deleted] Jul 09 '17
You could use a struct instead of byte array.
2
u/Rohansi Jul 08 '17
What is the array being used for? The allocation can only be eliminated if you either don't use an array or reuse the same instance.