Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BenchmarkDotNet snippet to compare Span<byte> to raw pointer #370

Merged
merged 3 commits into from
May 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
badrishc marked this conversation as resolved.
Show resolved Hide resolved
{
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;
}
}
}
}
}