- Home /
UNET & IL2CPP memory allocation?
So, after taking a peek in the internal code for UNET it seems that normally, for serializing some simple numeric types, UNET uses a union struct so that it can for example it can take a float, get the uint formed by the raw bytes of that float, and then serialize that, without generating memory. But, apparently, in the case of IL2CPP, it doesn't do that. Instead, it uses BitConverter.GetBytes to get a byte array of the float or double and serializes the byte array.
The problem is, as far as I can tell this means a four-byte array is allocated for every single float which is serialized to a stream when compiling for IL2CPP.
Am I missing something, or does serializing floats really allocate that memory? It seems like IL2CPP should be able to handle unions, given that C++ definitely supports this sort of logic.
This certainly should not be the case. I'm not specifically familiar with the UNET code you are referring to though. Can you provide more details about which code this is? Or is this something that can be caused without UNET? If you can provide a standalone test case to reproduce this, that would really help us. Thanks!
It's in NetworkWriter.cs, starting on line 261 (looking at the source in BitBucket). It appears that it uses a union struct normally, but that part is completely compiled out if INCLUDE_IL2CPP is defined, in favor of BitConverter.ToUInt32(BitConverter.GetBytes(value), 0), which as far as I can tell would allocate a byte array because of the call to GetBytes.
Answer by PrimalCoder · Oct 29, 2017 at 01:24 PM
I have not looked in the latest versions to see if it's still true, but at the time you asked the question it really was true that serializing floats allocated memory as you described.
Our solution was to convert the floats to ints before serialization using a utility class like this one FloatConversion.cs