using System.Security.Cryptography; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Order; namespace Benchmarks; [SimpleJob(RuntimeMoniker.NativeAot70)] [SimpleJob(RuntimeMoniker.Net70)] [SimpleJob(RuntimeMoniker.Net60)] [Orderer(SummaryOrderPolicy.FastestToSlowest)] [RankColumn] [MemoryDiagnoser] [ExceptionDiagnoser] [ThreadingDiagnoser] public class BinaryConversionBenchmarks { private byte[] data; private int offset; [GlobalSetup] public void Setup() { data = RandomNumberGenerator.GetBytes(4000); offset = RandomNumberGenerator.GetInt32(0, 3500); } [Benchmark] public Int16 BitConverterTest() { return BitConverter.ToInt16(data, offset); } [Benchmark] public Int16 BinaryReader() { using MemoryStream ms = new MemoryStream(data); using BinaryReader reader = new BinaryReader(ms); reader.BaseStream.Position = offset; return reader.ReadInt16(); } [Benchmark] public Int16 BinaryPrimitives() { return System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian( new ArraySegment(data, offset, sizeof(short))); } }