hangingfan / Technical-Blog

-----------------个人博客-----------------
1 stars 0 forks source link

difference between stack and heap #9

Open hangingfan opened 6 years ago

hangingfan commented 6 years ago

1: pointer jump speed is the same between stack and heap 2: reason why stack is faster than heap 1) we can only change the stack pointer position when allocating the stack, but in heap, we need to scan the array that holds all the available space , and find the first available space for current allocating need. then delete the room from the array and return the remain space back to the array. 2) we can only change the stack pointer position when recycle the stack space,but in heap, we still need to put the recycle space information back to the array for next use.

warning: the space did't initialize or reset when allocating or recycle for both the stack and the heap. Here is the example showing this: 1----C++ no optimize ----stack

void func()
{
    int data = 10;
}

void func1()
{
    int data1;
    std::cout <<"data1:"<< data1<<"\n";
}

int main()
{
    func();
    func1();
    return 0;
}

result: 10

2-----heap

#include<iostream>

void func()
{
    int* temp = new int[100];
    for(int i = 0; i< 100; ++i)
    {
        temp[i] = i;
    };
    std::cout <<"temp:"<< temp[78]<<"\n";
    delete[] temp;
}

void func1()
{
    int* temp1 = new int[100];
    std::cout <<"temp1:"<< temp1[78]<<"\n";
}

int main()
{
    func();
    func1();
    return 0;
}

result: 78

the more detailed explanation is in the <Pro .NET Performance>

Contrary to popular belief, there isn’t that much of a difference between stacks and heaps in a .NET process. Stacks and heaps are nothing more than ranges of addresses in virtual memory, and there is no inherent advantage in the range of addresses reserved to the stack of a particular thread compared to the range of addresses reserved for the managed heap. Accessing a memory location on the heap is neither faster nor slower than accessing a memory location on the stack. There are several considerations that might, in certain cases, support the claim that memory access to stack locations is faster, overall, than memory access to heap locations. Among them:

With that said, you should not be moving all your allocations to the stack! Thread stacks on Windows are limited, and it is easy to exhaust the stack by applying injudicious recursion and large stack allocations.