Skip to content

Instantly share code, notes, and snippets.

@mattwarren
Forked from goldshtn/stackalloc-benchmark.cs
Last active September 2, 2015 13:50
Show Gist options
  • Save mattwarren/babb1ffc195dbc35b37c to your computer and use it in GitHub Desktop.
Save mattwarren/babb1ffc195dbc35b37c to your computer and use it in GitHub Desktop.
Benchmark for comparing stackalloc to heap allocations for small, medium, and large arrays.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackAllocVsHeapAlloc
{
public static class Sandbox
{
private const int ITERATIONS = 10000;
private const int REPETITIONS = 5;
public static int ArraySize = 86000;
private static void Measure(string what, Action action)
{
action(); // warm up
double[] results = new double[REPETITIONS];
for (int i = 0; i < REPETITIONS; ++i)
{
Stopwatch sw = Stopwatch.StartNew();
action();
results[i] = sw.Elapsed.TotalMilliseconds;
}
Console.WriteLine("{0} - AVG = {1}, MIN = {2}, MAX = {3}",
what, results.Average(), results.Min(), results.Max());
}
public static void Go()
{
Console.WriteLine("Array size: " + ArraySize);
Measure("Heap Array ", () =>
{
for (int i = 0; i < ITERATIONS; ++i)
{
GetSquare(i % ArraySize);
}
});
Measure("Stack Array", () =>
{
for (int i = 0; i < ITERATIONS; ++i)
{
GetSquareStack(i % ArraySize);
}
});
}
public static int GetSquare(int value)
{
int[] someNumbers = new int[ArraySize];
for (int i = 0; i < someNumbers.Length; ++i)
{
someNumbers[i] = value;
}
return someNumbers[value];
}
public unsafe static int GetSquareStack(int value)
{
int* someNumbers = stackalloc int[ArraySize];
for (int i = 0; i < ArraySize; ++i)
{
someNumbers[i] = value;
}
return someNumbers[value];
}
}
class Program
{
static void Main(string[] args)
{
for (int i = 10; i < 5000; i += 500)
{
Sandbox.ArraySize = i;
Sandbox.Go();
}
for (int i = 6000; i < 100000; i += 10000)
{
Sandbox.ArraySize = i;
Sandbox.Go();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment