-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Labels
Milestone
Description
Here is my test code:
public class PtrBenchmarkTest
{
private readonly byte[] buff = new byte[Marshal.SizeOf<StructObject>()];
public PtrBenchmarkTest()
{
var obj = new StructObject();
obj.Symbol = "rb2101";
obj.Exchange = 12;
obj.Px = 54.90F;
unsafe
{
fixed (byte* bp = buff)
{
Marshal.StructureToPtr(obj, (IntPtr)bp, false);
}
}
}
[Benchmark]
public StructObject PtrToStructure()
{
unsafe
{
fixed (byte* bp = buff)
{
return (StructObject)Marshal.PtrToStructure((IntPtr)bp, typeof(StructObject));
}
}
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class StructObject
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string Symbol;
[MarshalAs(UnmanagedType.I8)]
public Int64 Exchange;
[MarshalAs(UnmanagedType.R4)]
public float Px;
};
netcore3.1 Benchmark test result:
Method | Mean | Error | StdDev | Median |
---|---|---|---|---|
PtrToStructure | 522.44 ns | 29.418 ns | 84.878 ns | 503.07 ns |
net5.0 Benchmark test result:
Method | Mean | Error | StdDev | Median |
---|---|---|---|---|
PtrToStructure | 4,098.30 ns | 132.015 ns | 372.350 ns | 4,004.22 ns |
os: windows 10
gchernis and d79ima