lnobad / lidgren-network-gen3

Automatically exported from code.google.com/p/lidgren-network-gen3
0 stars 0 forks source link

NetOutgoingMessage.Write(float): BitConverter.GetBytes memory hog #76

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Create an outgoing message
2. Write n floats to it
3. see how much memory BitConverter.GetBytes allocated

What is the expected output? What do you see instead?

BitConverter.GetBytes allocates an array of 4 bytes per float.
This makes it infeasable to use Write(float) for large numbers of floats.

What version of the product are you using? On what operating system?

3.x under Unity 3.x

Please provide any additional information below.

A better way is to make a [static] single float array, write the float into it, 
then use System.Buffer.BlockCopy to copy from the float array into the 
destination array or other byte array. That way no memory is allocated.

I recently moved away from BinaryReader/Writer to an internal class that uses 
BlockCopy to avoid the allocations and had a huge memory decrease.

Original issue reported on code.google.com by martin.b...@gmail.com on 8 Jul 2011 at 3:24

GoogleCodeExporter commented 9 years ago
[deleted comment]
GoogleCodeExporter commented 9 years ago
A static array would make separate threads each using their own message 
instance stomp on eachother. If you add the UNSAFE define to NetOutgoingMessage 
it will use unsafe code to avoid the allocation however. Still looking for a 
way to do this safely.

Original comment by lidg...@gmail.com on 7 Jan 2012 at 9:55

GoogleCodeExporter commented 9 years ago
hi,
you can create a union struct to convert a float value.

[StructLayout(LayoutKind.Explicit)] 
public struct SampleUnion
{
  [FieldOffset(0)] public float SingleValue;
  [FieldOffset(0)] public byte B1;
  [FieldOffset(1)] public byte B2;
  [FieldOffset(2)] public byte B3;
  [FieldOffset(3)] public byte B4;
}

Original comment by kutsa...@web.de on 19 Jan 2012 at 7:12

GoogleCodeExporter commented 9 years ago
Thanks; I had forgot about the union trick! Added in revision 282

Original comment by lidg...@gmail.com on 20 Jan 2012 at 9:53