From ed4b9ab3c34bdc33b46c54ca92cc551fb13b2fb1 Mon Sep 17 00:00:00 2001 From: Badrish Chandramouli Date: Wed, 8 May 2024 17:12:41 -0700 Subject: [PATCH] BenchmarkDotNet snippet to compare Span to raw pointer (#370) * BenchmarkDotNet snippet to compare Span to raw pointer work. * nits * nit --- benchmark/BDN.benchmark/SpanVsPointer.cs | 68 ++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 benchmark/BDN.benchmark/SpanVsPointer.cs diff --git a/benchmark/BDN.benchmark/SpanVsPointer.cs b/benchmark/BDN.benchmark/SpanVsPointer.cs new file mode 100644 index 0000000000..147f6d863a --- /dev/null +++ b/benchmark/BDN.benchmark/SpanVsPointer.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +using System.Runtime.CompilerServices; +using BenchmarkDotNet.Attributes; + +namespace BDN.benchmark +{ + public unsafe class SpanVsPointer + { + const int Count = 1024; + + byte[] bytes; + byte* bytesPtr; + + [GlobalSetup] + public void GlobalSetup() + { + bytes = GC.AllocateArray(Count, true); + bytesPtr = (byte*)Unsafe.AsPointer(ref bytes[0]); + for (var ii = 0; ii < Count; ++ii) + bytes[ii] = (byte)ii; + } + + [BenchmarkCategory("Swap"), Benchmark(Baseline = true)] + public void Pointer() + { + byte* pointer = bytesPtr; + byte* end = pointer + Count - 1; + while (pointer < end) + { + var tmp = *pointer; + *pointer = *++pointer; + *pointer = tmp; + } + } + + [BenchmarkCategory("Swap"), Benchmark] + public void Span() + { + var span = new Span(bytesPtr, Count); + int i = 0; + while (i < Count - 1) + { + var tmp = span[i]; + span[i] = span[++i]; + span[i] = tmp; + } + } + + [BenchmarkCategory("Swap"), Benchmark] + public void SpanToPointer() + { + var span = new Span(bytesPtr, Count); + fixed (byte* ptr = span) + { + byte* pointer = ptr; + byte* end = pointer + Count - 1; + while (pointer < end) + { + var tmp = *pointer; + *pointer = *++pointer; + *pointer = tmp; + } + } + } + } +} \ No newline at end of file