cstackdata-segment

Data segment vs stack


A global variable is allocated in the data segment, while a local one stays in the stack. I know that accessing a variable stored in the heap is slower than accessing a local variable, but I don't know if accessing a local variable is faster than accessing a global one. Does it depend on the compiler? Are the differences significant or not?


Solution

  • Stack and head are only implementation details, meaning that they could depend on the compiling environment. The C standard only defines the linkage and storage duration of identifiers. But you are right, stack, heap and data segment are the common implementation.

    But you are wrong when you say accessing a variable stored in the heap is slower than accessing a local variable. Allocating and deallocating dynamic memory is indeed more complex and takes more time than using automatic variables, but during their lifetime, accessing (be it for reading or writing) costs exactly the same - at least on common infrastructure. What will make the difference is:

    But both can happen the same for dynamic, automatic or static data...