Skip to content

Instantly share code, notes, and snippets.

@Scooletz
Last active April 21, 2017 08:35
Show Gist options
  • Save Scooletz/2aeee833894e8239bfdb6d06e036118d to your computer and use it in GitHub Desktop.
Save Scooletz/2aeee833894e8239bfdb6d06e036118d to your computer and use it in GitHub Desktop.
ThreadStatic vs stackalloc
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace Locals
{
class Program
{
static void Main(string[] args) => BenchmarkRunner.Run<LocalsBenchmark>();
}
public class LocalsBenchmark
{
public const int N = 32;
static readonly ArrayPool<byte> Pool = ArrayPool<byte>.Shared;
public LocalsBenchmark()
{
ByteArray.Recycle(new ByteArray());
ByteArray.Recycle(ByteArray.GetRecycled());
Pool.Return(Pool.Rent(N));
}
[Benchmark]
public unsafe void Stackalloc()
{
byte* bytes = stackalloc byte[N];
for (var i = 0; i < N; i++)
{
bytes[i] = 1;
}
KeepAlive(bytes);
}
[Benchmark]
public void Threadstatic()
{
var array = ByteArray.GetRecycled();
var bytes = array.Bytes;
try
{
for (var i = 0; i < N; i++)
{
bytes[i] = 1;
}
}
finally
{
ByteArray.Recycle(array);
}
}
[Benchmark]
public void ArrayPool()
{
var bytes = Pool.Rent(N);
try
{
for (var i = 0; i < N; i++)
{
bytes[i] = 1;
}
}
finally
{
Pool.Return(bytes);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static unsafe void KeepAlive(byte* ptr) { }
}
public class ByteArray
{
public byte[] Bytes = new byte[LocalsBenchmark.N];
[ThreadStatic] static ByteArray _lastArray;
public static ByteArray GetRecycled()
{
var result = _lastArray;
_lastArray = null;
return result;
}
public static void Recycle(ByteArray array)
{
if (array != null)
{
_lastArray = array;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment