Consider the following method (used in a factory method):
private Packet(byte[] rawBytes, int startIndex)
{
m_packetId = BitConverter.ToUInt32(rawBytes, startIndex);
m_dataLength = BitConverter.ToUInt16(rawBytes, startIndex + 4);
if (this.Type != PacketType.Data)
return;
m_bytes = new byte[m_dataLength];
rawBytes.CopyTo(m_bytes, startIndex + Packet.HeaderSize);
}
The last two lines of code strike me wasteful. Allocating more memory and populating it with values from memory seems silly.
With unmanaged code, something like this is possible:
m_bytes = (rawBytes + (startIndex + Packet.HeaderSize));
(I didn’t run it through a compiler so syntax is probably off, but you can see it’s just a matter of pointer manipulation.)
I ran into a similar problem the other day when an API returned a byte[] array that was really a short[] array.
Are these types of array permutations just the cost of using managed code or is there a new school of thinking that I’m just missing?
Thanks in advance.
Have you considered restructuring so that maybe the copy is not necessary?
First option: store a reference to
rawBytesinm_bytesand store the offset that needs to be added to all accesses into this byte array.Second option: make
m_bytesaMemoryStreaminstead, constructed from the buffer, an offset and a length; this constructor also does not copy the byte buffer and just allows access to the specified sub-segment.Keep in mind though that the price of avoiding the copy operation is that the
rawBytesandm_bytes(array or stream) will be aliases, so changes to one will change the other too.