2023-10-12 07:15:34 +00:00
|
|
|
namespace Benchmarks;
|
2023-08-12 21:02:59 +00:00
|
|
|
|
|
|
|
using System.Security.Cryptography;
|
2023-08-10 20:07:40 +00:00
|
|
|
using BenchmarkDotNet.Attributes;
|
|
|
|
using BenchmarkDotNet.Order;
|
|
|
|
|
|
|
|
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
|
2023-11-08 14:34:09 +00:00
|
|
|
[Config(typeof(GenericConfig))]
|
2023-08-10 20:07:40 +00:00
|
|
|
public class BinaryConversionBenchmarks
|
|
|
|
{
|
2023-10-27 17:47:17 +00:00
|
|
|
private byte[] _data = null!;
|
|
|
|
private int _offset;
|
2023-08-10 20:07:40 +00:00
|
|
|
|
|
|
|
[GlobalSetup]
|
|
|
|
public void Setup()
|
|
|
|
{
|
2023-10-27 17:47:17 +00:00
|
|
|
this._data = RandomNumberGenerator.GetBytes(4000);
|
|
|
|
this._offset = RandomNumberGenerator.GetInt32(0, 3500);
|
2023-08-10 20:07:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
[Benchmark]
|
2023-10-27 17:47:17 +00:00
|
|
|
public short BitConverterTest() => BitConverter.ToInt16(this._data, this._offset);
|
2023-08-10 20:07:40 +00:00
|
|
|
|
|
|
|
[Benchmark]
|
2023-08-11 09:31:30 +00:00
|
|
|
public short BinaryReader()
|
2023-08-10 20:07:40 +00:00
|
|
|
{
|
2023-10-27 17:47:17 +00:00
|
|
|
using var ms = new MemoryStream(this._data);
|
2023-08-11 09:31:30 +00:00
|
|
|
using var reader = new BinaryReader(ms);
|
2023-10-27 17:47:17 +00:00
|
|
|
reader.BaseStream.Position = this._offset;
|
2023-08-10 20:07:40 +00:00
|
|
|
return reader.ReadInt16();
|
|
|
|
}
|
|
|
|
|
|
|
|
[Benchmark]
|
2023-08-11 09:31:30 +00:00
|
|
|
public short BinaryPrimitives() =>
|
|
|
|
System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(
|
2023-10-27 17:47:17 +00:00
|
|
|
new ArraySegment<byte>(this._data, this._offset, sizeof(short)));
|
2023-08-11 09:31:30 +00:00
|
|
|
}
|