AyCode.Core/AyCode.Benchmark/Workloads/Scenarios/MemoryPackBenchmark.cs

50 lines
2.1 KiB
C#

using AyCode.Core.Serializers;
using AyCode.Core.Tests.TestModels;
using MemoryPack;
using System.Runtime.CompilerServices;
namespace AyCode.Core.Benchmarks.Workloads.Scenarios;
/// <summary>
/// MemoryPack benchmark, Byte[] I/O mode. The SOTA baseline AcBinary is compared against in every
/// cell. WireMode-aligned options via <see cref="BenchmarkOptions.GetMemPack"/> so Compact ↔ UTF-8
/// and FastWire ↔ UTF-16 are apples-to-apples on the string-encoding axis.
/// </summary>
public sealed class MemoryPackBenchmark<T> : ISerializerBenchmark where T : class
{
private readonly T _order;
private readonly MemoryPackSerializerOptions _options;
private readonly byte[] _serialized;
public BenchmarkEngine Engine => BenchmarkEngine.MemoryPack;
public BenchmarkIoMode IoMode => BenchmarkIoMode.ByteArray;
public BenchmarkDispatchMode DispatchMode => BenchmarkDispatchMode.SGen; // MemoryPack always uses [MemoryPackable] source-generated formatters
public Type OrderType => typeof(T);
public string OptionsPreset { get; }
public int SerializedSize => _serialized.Length;
public long SetupSerializeAllocBytes => 0;
public long SetupDeserializeAllocBytes => 0;
public string? OptionsDescription => $"StringEncoding={_options.StringEncoding}";
public MemoryPackBenchmark(T order, WireMode wireMode, string optionsPreset)
{
_order = order;
OptionsPreset = optionsPreset;
_options = BenchmarkOptions.GetMemPack(wireMode);
_serialized = MemoryPackSerializer.Serialize(order, _options);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void Serialize() => MemoryPackSerializer.Serialize(_order, _options);
[MethodImpl(MethodImplOptions.NoInlining)]
public void Deserialize() => MemoryPackSerializer.Deserialize<T>(_serialized, _options);
public bool VerifyRoundTrip()
{
var bytes = MemoryPackSerializer.Serialize(_order, _options);
var roundTripped = MemoryPackSerializer.Deserialize<T>(bytes, _options);
return RoundTripValidator.DeepEqualsViaJson(_order, roundTripped);
}
}