Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data segment vs stack [closed]

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?

like image 629
Francesco Di Lauro Avatar asked Apr 23 '26 17:04

Francesco Di Lauro


1 Answers

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:

  • is the data in processor cache or in level 2 cache (speeds up access)
  • is the data in a currently swapped off page that needs to be reloaded from disk (slows down access)

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

like image 147
Serge Ballesta Avatar answered Apr 25 '26 10:04

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!