continuity/Benchmarks/BinaryConversionBenchmarks.cs

45 lines
1.2 KiB
C#
Raw Normal View History

2023-10-12 07:15:34 +00:00
namespace Benchmarks;
using System.Security.Cryptography;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Order;
[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()
{
2023-08-11 09:31:30 +00:00
this.data = RandomNumberGenerator.GetBytes(4000);
this.offset = RandomNumberGenerator.GetInt32(0, 3500);
}
[Benchmark]
2023-08-11 09:31:30 +00:00
public short BitConverterTest() => BitConverter.ToInt16(this.data, this.offset);
[Benchmark]
2023-08-11 09:31:30 +00:00
public short BinaryReader()
{
2023-08-11 09:31:30 +00:00
using var ms = new MemoryStream(this.data);
using var reader = new BinaryReader(ms);
reader.BaseStream.Position = this.offset;
return reader.ReadInt16();
}
[Benchmark]
2023-08-11 09:31:30 +00:00
public short BinaryPrimitives() =>
System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(
new ArraySegment<byte>(this.data, this.offset, sizeof(short)));
}