Hello!
I've been working on a network layer, and I've settled on using structs to represent (yet non-serialized) packets since I can stackalloc them and pass them with in to avoid copies.
For context, packets are created as generic like this:
T packetAsModel = new T();
packetAsModel.FromRawBuffer(buffer);
_listeners.Invoke(in packetAsModel, in header);
After analyzing the IL produced, I can confirm that the handlers themselves don't create any copies when they receive and read a packet struct.
However, writing the packet struct inside a byte buffer (to later be sent) does cause a copy even if the method is marked as readonly.
Example of a struct packet:
https://paste.mod.gg/lpycjrtecjre/0
The generated IL for both a handler AND a ToRawBuffer() call:
https://paste.mod.gg/ooxyldgumfzm/0
Line 5 here shows the instruction that creates the defensive copy despite the method being readonly and not modifying the struct.
I'd appreciate if anyone could tell me why this happens/some possible alternatives!