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

Discussion in 'Programming and Scripting' started by AceInfinity, Dec 12, 2012.

  1. AceInfinity

    AceInfinity Senior Member
    Microsoft MVP

    Joined:
    Aug 12, 2011
    Messages:
    159
    Likes Received:
    11
    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];
    }
     

Share This Page

Loading...