There are three reasons why I have some issues with many other implementations I've been seeing:
- The implementation uses managed pointers to access the byte array as though they are unmanaged pointers. Unfortunately, this doesn't really work.
- The implementation locks the managed pointer on the byte array, which affects garbage collection and can seriously affect throughput. Locking should be avoided for copying small structs around.
- The implementation copies the data properly into an unmanaged pointer first, but it uses a heap allocation method to get the memory, which for small structures is somewhat suboptimal - stack memory is probably better for this sort of thing.
public sealed abstract class BinaryStreamSupport
{
private BinaryStreamSupport() { }
public static T ReadStruct
{
int size;
byte[] data;
size = Marshal.SizeOf(typeof(T));
data = new byte[size];
s.Read(data, 0, size);
return _ReadStruct
}
public static T ReadStruct
{
return _ReadStruct
}
private static T _ReadStruct
{
T returnValue;
unsafe
{
byte* stackDataPtr = stackalloc byte[size];
IntPtr stackData = new IntPtr(stackDataPtr);
Marshal.Copy(data, start, stackData, size);
returnValue = (T)Marshal.PtrToStructure(stackData, typeof(T));
}
return returnValue;
}
}
No comments:
Post a Comment