How to convert floats/doubles to raw bytes without generating garbage?
Hi!
I have a network solution using UNET LLAPI. I use my own class to send and receive bytes, and I currently use BinaryReader and BinaryWriter with a MemoryStream. The problem is, BinaryWriter.Write(float) generates garbage (44 Bytes for each float) and I don't want any garbage collection. This problem also occurs with double, but not with BinaryReader and/or integer, byte, char etc. BinaryFormatter is worse in every way (garbage + bytes used).
I looked around, it seems that BinaryWriter.Write(float) uses BitConverter.GetBytes(), which creates an array each time it is called. Also I believe that it's only the Unity .NET version that does this issue.
I don't want to use my own function (which is the same than BinaryWriter.Write(float) inside .NET v4 library) because it uses unsafe code and I want to be able to target the WebPlayer platform.
I also want a conversion without any loss of accuracy, and that doesn't use more than 4 bytes per float once it's converted. The speed of conversion also matters but less than accuracy and space.
Thank you.
Answer by ttRevan · Nov 06, 2015 at 08:07 PM
You can use UNET NetworkWriter that is used in HLAPI, it doesn't generate garbage and uses something like C union imitation for float-to-int conversion.
BTW, thanks for figuring out BinaryWriter generate garbage, I am using it by myself :)
I don't see any hint in your link that indicates that I could use NetworkWriter to convert a float into byte[]. Is it only through a GameObject? EDIT: Okay the documentation is incomplete. It seems to do what I was looking for, thanks!
Your answer

Follow this Question
Related Questions
NetworkIdentity.netID to int 3 Answers
Timespan to int total seconds 0 Answers
[UNET 5.2] Multiple local authority for 1 object? 0 Answers
Connecting SQL with Unity 0 Answers