-
Notifications
You must be signed in to change notification settings - Fork 520
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
BenchmarkDotNet snippet to compare Span<byte> to raw pointer (#370)
* BenchmarkDotNet snippet to compare Span<byte> to raw pointer work. * nits * nit
- Loading branch information
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} | ||
} | ||
} |