Skip to content

Commit

Permalink
BenchmarkDotNet snippet to compare Span<byte> to raw pointer (#370)
Browse files Browse the repository at this point in the history
* BenchmarkDotNet snippet to compare Span<byte> to raw pointer work.

* nits

* nit
  • Loading branch information
badrishc committed May 9, 2024
1 parent 5cce676 commit ed4b9ab
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions benchmark/BDN.benchmark/SpanVsPointer.cs
Original file line number Diff line number Diff line change
@@ -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<byte>(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<byte>(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<byte>(bytesPtr, Count);
fixed (byte* ptr = span)
{
byte* pointer = ptr;
byte* end = pointer + Count - 1;
while (pointer < end)
{
var tmp = *pointer;
*pointer = *++pointer;
*pointer = tmp;
}
}
}
}
}

0 comments on commit ed4b9ab

Please sign in to comment.