Windows 7 [C#] - stack vs. heap allocation

AceInfinity

Senior Member
Microsoft MVP
Here's a demonstration and benchmark test I did on allocating to the stack vs. allocating on the heap. I combined both allocation and retrieval into each method for each allocation destination, and the results are below.

Note: There are benefits of each, although for speed, allocation on the stack is much faster if you need that for performance. The downside is that the heap is a much larger block of space than the stack, which is usually limited. Therefore, you can get a stack overflow exception if you try to push too much to the stack before it's pop'd off.

Upon declaration to the stack, for instance, this line:
Code:
int* i = stackalloc int[100000];

Will actually measure how much space we need to allocate 100000 signed 32 bit integer values on the stack, which is 4 bytes * 100000 = 400000bytes.

Code:
private unsafe void Method1()
{
    int tmp;
    int* i = stackalloc int[100000];
    for (int n = 0; n < 100000; n++)
        i[n] = 0;
    for (int x = 0; x < 100000; x++) tmp = i[x];
}

private unsafe void Method2()
{
    int tmp;
    int[] i = new int[100000];
    for (int n = 0; n < 100000; n++)
        i[n] = 0;
    for (int x = 0; x < 100000; x++) tmp = i[x];
}

(Benchmark Starting... 10 averages of 100 runs)

# Method1
> [Average 1/10] Complete - 2720.28 ticks
> [Average 2/10] Complete - 2471.68 ticks
> [Average 3/10] Complete - 2502.54 ticks
> [Average 4/10] Complete - 2510.59 ticks
> [Average 5/10] Complete - 2508.63 ticks
> [Average 6/10] Complete - 2501.61 ticks
> [Average 7/10] Complete - 2776.15 ticks
> [Average 8/10] Complete - 2450.17 ticks
> [Average 9/10] Complete - 2451.4 ticks
> [Average 10/10] Complete - 2645.82 ticks
# Result: 2553.887 ticks

# Method2
> [Average 1/10] Complete - 5423.1 ticks
> [Average 2/10] Complete - 5580.77 ticks
> [Average 3/10] Complete - 5003.69 ticks
> [Average 4/10] Complete - 5214.7 ticks
> [Average 5/10] Complete - 4891.69 ticks
> [Average 6/10] Complete - 5313.5 ticks
> [Average 7/10] Complete - 5554.04 ticks
> [Average 8/10] Complete - 5269.06 ticks
> [Average 9/10] Complete - 5384.69 ticks
> [Average 10/10] Complete - 5209.16 ticks
# Result: 5284.44 ticks
 
Back
Top