O
O.B.
I have a structure named EntityState with an explicit layout.
The following two operations exist within the class to return a byte
array representing the current object. Upon executing them each a
million times, I've learned that the ToRaw2() operation is twice as fast
as ToRaw().
So is it always safe to use the ToRaw2() operation or is there some gain
in using Marshal's Copy operation?
unsafe public byte[] ToRaw()
{
byte[] byteArray = new byte[EntityState.PDU_SIZE];
IntPtr pointer = Marshal.AllocHGlobal(EntityState.PDU_SIZE);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, EntityState.PDU_SIZE);
Marshal.FreeHGlobal(pointer);
return byteArray;
}
unsafe public byte[] ToRaw2()
{
byte[] byteArray = new byte[EntityState.PDU_SIZE];
fixed (byte* ptr = byteArray)
{
*((EntityState*)ptr) = this;
}
return byteArray;
}
The following two operations exist within the class to return a byte
array representing the current object. Upon executing them each a
million times, I've learned that the ToRaw2() operation is twice as fast
as ToRaw().
So is it always safe to use the ToRaw2() operation or is there some gain
in using Marshal's Copy operation?
unsafe public byte[] ToRaw()
{
byte[] byteArray = new byte[EntityState.PDU_SIZE];
IntPtr pointer = Marshal.AllocHGlobal(EntityState.PDU_SIZE);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, EntityState.PDU_SIZE);
Marshal.FreeHGlobal(pointer);
return byteArray;
}
unsafe public byte[] ToRaw2()
{
byte[] byteArray = new byte[EntityState.PDU_SIZE];
fixed (byte* ptr = byteArray)
{
*((EntityState*)ptr) = this;
}
return byteArray;
}