using AyCode.Core.Serializers; using AyCode.Core.Tests.TestModels; using MemoryPack; using System.Buffers; using System.Runtime.CompilerServices; namespace AyCode.Core.Benchmarks.Workloads.Scenarios; /// /// Benchmarks MemoryPack via the IBufferWriter overload, allocating a FRESH ArrayBufferWriter on EVERY call. /// Apples-to-apples counterpart to . /// public sealed class MemoryPackFreshBufferWriterBenchmark : 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.BufWrNew; 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 MemoryPackFreshBufferWriterBenchmark(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() { var abw = new ArrayBufferWriter(); MemoryPackSerializer.Serialize(abw, _order, _options); } // BufWr semantic: read from a ReadOnlySequence overload (apples-to-apples with AcBinary's // BufWr Deser path). MemoryPack's ROS overload also single-segment-fast-paths internally. [MethodImpl(MethodImplOptions.NoInlining)] public void Deserialize() => MemoryPackSerializer.Deserialize(new ReadOnlySequence(_serialized), _options); public bool VerifyRoundTrip() { var abw = new ArrayBufferWriter(); MemoryPackSerializer.Serialize(abw, _order, _options); var roundTripped = MemoryPackSerializer.Deserialize(new ReadOnlySequence(abw.WrittenMemory), _options); return RoundTripValidator.DeepEqualsViaJson(_order, roundTripped); } }