Structure to Byte Array - Which is better? Marshal Copy or FixedByte Assignment


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;
}
 
Ad

Advertisements

M

Mattias Sjögren

So is it always safe to use the ToRaw2() operation or is there some gain
in using Marshal's Copy operation?

ToRaw will handle a larger variety of structs. You can only use
pointers on a very restricted set of types in C#. But as long as it
works, it's fine to use ToRaw2.

If performance is your top priority then I guess ToRaw2 is the better
alternative. But I would also consider a third alternative that used
the BitConverter class to convert each member separately. The benefit
there is that the code doesn't require full trust to run.


Mattias
 
Ad

Advertisements

O

O.B.

ToRaw will handle a larger variety of structs. You can only use
pointers on a very restricted set of types in C#. But as long as it
works, it's fine to use ToRaw2.

If performance is your top priority then I guess ToRaw2 is the better
alternative. But I would also consider a third alternative that used
the BitConverter class to convert each member separately. The benefit
there is that the code doesn't require full trust to run.

Ah, very good. Just making sure that I wasn't missing anything
obvious. I'm trying to run as close to real-time as possible. Thank
you for the prompt reply.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top