I’m writing a quick save/load system, so you can basically tap “F5” and we use a MemoryStream/BinaryWriter combo to write out the game’s state. I’m reusing a single byte array as a buffer, in an attempt to not do a bunch of allocation every time a save occurs.
This all works great, but I’m seeing a lot of “GC.Alloc” rows appearing in the profiler. Upon further inspection, I found that there is one “GC.Alloc” call per call to BinaryWriter.Write(float), and each of these calls allocates 36B of memory. Floats are fairly common, so this ends up adding up quite a bit, to ultimately 152KB of memory allocation!
Upon further inspection, it’s possible for me to pack the float value into a “uint” (since they are both 4 bytes), and I no longer get that 36B allocation.
writer.Write(myFloat); // allocates 36B
writer.Write(ByteUtil.FloatToUInt(myFloat)); // allocates 0B
I guess ultimately my question is this: is it expected that BinaryWriter.Write(float) would allocate memory like this? Is it expected behavior, or is this a bug? Is there any way to know whether this is something that should be reported as a bug to Unity?
(Note: sorry for the horizontal rules, but this site is not properly formatting my paragraphs for some reason…)