2023-11-20 18:58:30 +00:00
|
|
|
// // Copyright (c) 2023 Timothy Schenk. Subject to the GNU AGPL Version 3 License.
|
|
|
|
|
2023-11-19 16:07:28 +00:00
|
|
|
using System.Buffers.Binary;
|
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;
|
|
|
|
|
2023-11-19 16:07:28 +00:00
|
|
|
namespace Benchmarks;
|
|
|
|
|
2023-08-10 20:07:40 +00:00
|
|
|
[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-11-13 18:32:47 +00:00
|
|
|
private int _writeBuffer;
|
2023-08-10 20:07:40 +00:00
|
|
|
|
|
|
|
[GlobalSetup]
|
|
|
|
public void Setup()
|
|
|
|
{
|
2023-11-19 16:07:28 +00:00
|
|
|
_data = RandomNumberGenerator.GetBytes(4000);
|
|
|
|
_offset = RandomNumberGenerator.GetInt32(0, 3500);
|
|
|
|
_writeBuffer = RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
|
2023-08-10 20:07:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
[Benchmark]
|
2023-11-19 16:07:28 +00:00
|
|
|
public short BitConverterParseTest()
|
|
|
|
{
|
|
|
|
return BitConverter.ToInt16(_data, _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-11-19 16:07:28 +00:00
|
|
|
using var ms = new MemoryStream(_data);
|
2023-08-11 09:31:30 +00:00
|
|
|
using var reader = new BinaryReader(ms);
|
2023-11-19 16:07:28 +00:00
|
|
|
reader.BaseStream.Position = _offset;
|
2023-08-10 20:07:40 +00:00
|
|
|
return reader.ReadInt16();
|
|
|
|
}
|
|
|
|
|
|
|
|
[Benchmark]
|
2023-11-19 16:07:28 +00:00
|
|
|
public short BinaryPrimitivesRead()
|
|
|
|
{
|
|
|
|
return BinaryPrimitives.ReadInt16LittleEndian(
|
|
|
|
new ArraySegment<byte>(_data, _offset, sizeof(short)));
|
|
|
|
}
|
2023-11-13 18:32:47 +00:00
|
|
|
|
|
|
|
[Benchmark]
|
|
|
|
public void BinaryPrimitivesWrite()
|
|
|
|
{
|
2023-11-19 16:07:28 +00:00
|
|
|
BinaryPrimitives.WriteInt32LittleEndian(_data.AsSpan(_offset, 4),
|
|
|
|
_writeBuffer);
|
2023-11-13 18:32:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
[Benchmark]
|
|
|
|
public void BitConverterCopy()
|
|
|
|
{
|
2023-11-19 16:07:28 +00:00
|
|
|
BitConverter.GetBytes(_writeBuffer).CopyTo(_data, _offset);
|
2023-11-13 18:32:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
[Benchmark]
|
|
|
|
public void BitConverterAssignment()
|
|
|
|
{
|
2023-11-19 16:07:28 +00:00
|
|
|
var bytes = BitConverter.GetBytes(_writeBuffer);
|
|
|
|
_data[_offset] = bytes[0];
|
|
|
|
_data[_offset + 1] = bytes[1];
|
|
|
|
_data[_offset + 2] = bytes[2];
|
|
|
|
_data[_offset + 3] = bytes[3];
|
2023-11-13 18:32:47 +00:00
|
|
|
}
|
2023-08-11 09:31:30 +00:00
|
|
|
}
|