Skip to content

Instantly share code, notes, and snippets.

@goldshtn
Created October 17, 2013 09:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save goldshtn/7021608 to your computer and use it in GitHub Desktop.
Save goldshtn/7021608 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