From 293b65a8562fe5cbb465ebdfd3600c84be990740 Mon Sep 17 00:00:00 2001 From: Timothy Schenk Date: Mon, 13 Nov 2023 19:32:47 +0100 Subject: [PATCH] feat: add benchmark for writing to span/array of bytes --- Benchmarks/BinaryConversionBenchmarks.cs | 29 ++++++++++++++++++++++-- Benchmarks/GenericConfig.cs | 7 ------ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/Benchmarks/BinaryConversionBenchmarks.cs b/Benchmarks/BinaryConversionBenchmarks.cs index 3252171..ff14eee 100644 --- a/Benchmarks/BinaryConversionBenchmarks.cs +++ b/Benchmarks/BinaryConversionBenchmarks.cs @@ -10,16 +10,18 @@ public class BinaryConversionBenchmarks { private byte[] _data = null!; private int _offset; + private int _writeBuffer; [GlobalSetup] public void Setup() { this._data = RandomNumberGenerator.GetBytes(4000); this._offset = RandomNumberGenerator.GetInt32(0, 3500); + this._writeBuffer = RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue); } [Benchmark] - public short BitConverterTest() => BitConverter.ToInt16(this._data, this._offset); + public short BitConverterParseTest() => BitConverter.ToInt16(this._data, this._offset); [Benchmark] public short BinaryReader() @@ -31,7 +33,30 @@ public class BinaryConversionBenchmarks } [Benchmark] - public short BinaryPrimitives() => + public short BinaryPrimitivesRead() => System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian( new ArraySegment(this._data, this._offset, sizeof(short))); + + [Benchmark] + public void BinaryPrimitivesWrite() + { + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(this._data.AsSpan(_offset, 4), + this._writeBuffer); + } + + [Benchmark] + public void BitConverterCopy() + { + BitConverter.GetBytes(this._writeBuffer).CopyTo(this._data, this._offset); + } + + [Benchmark] + public void BitConverterAssignment() + { + var bytes = BitConverter.GetBytes(this._writeBuffer); + this._data[this._offset] = bytes[0]; + this._data[this._offset + 1] = bytes[1]; + this._data[this._offset + 2] = bytes[2]; + this._data[this._offset + 3] = bytes[3]; + } } diff --git a/Benchmarks/GenericConfig.cs b/Benchmarks/GenericConfig.cs index 0dd812e..903dbf4 100644 --- a/Benchmarks/GenericConfig.cs +++ b/Benchmarks/GenericConfig.cs @@ -27,12 +27,5 @@ public class GenericConfig : ManualConfig .AddAnalyser(MinIterationTimeAnalyser.Default, OutliersAnalyser.Default, RuntimeErrorAnalyser.Default, EnvironmentAnalyser.Default) .AddColumn(RankColumn.Arabic).AddExporter(CsvExporter.Default, MarkdownExporter.Default); - AddJob(Job.Default - .WithRuntime(CoreRuntime.Core60)) - .AddDiagnoser(ThreadingDiagnoser.Default, MemoryDiagnoser.Default, - EventPipeProfiler.Default) - .AddAnalyser(MinIterationTimeAnalyser.Default, OutliersAnalyser.Default, - RuntimeErrorAnalyser.Default, EnvironmentAnalyser.Default) - .AddColumn(RankColumn.Arabic).AddExporter(CsvExporter.Default, MarkdownExporter.Default); } }