Hacker News new | ask | show | jobs
by headPoet 1109 days ago
"anything stored in that pointer to memory you got back from malloc() is stored in an area of ram called "the heap", which is moderately slower to access than it is to access the stack." Is this true, or a myth? Ignoring the allocation cost and access patterns making cache misses more likely, surely memory is just memory
3 comments

By definition, everything on the heap got where it is dynamically, so the minimum number of pointers to chase to find it is 1.

In contrast, what’s where on the stack can often be (and often must be) known statically by the compiler and accessed directly, even moved entirely out of memory and into a register. (It’s possible to do this with suitably constrained dynamic allocations, but the optimization is much harder.)

Some architectures (e.g. the 65816, the 6502's "big brother" used in the Apple IIgs) include stack pointer relative addressing modes, which will complete the memory read and return data faster than the same instruction with a full address encoded.
Many architectures have hardware support for stacks, which could be slightly faster than arbitrary load/stores. Only works in the function owning the stack frame of course, if you pass a pointer to a stack object somewhere else, it's back to being normal memory.
I'm pretty sure this is still the case. I'm not sure how cross-platform that assumption is (it won't work in Go where it has heapstacks I don't think), but classically yeah the stack is put is slightly faster memory with fewer access barriers.
I believe that’s inaccurate, at least on a modern CPU. The bookkeeping for the stack is faster, since ‘allocating’ and ‘deallocating’ is just subtracting from and adding to a register. And the area of the stack in active use at any given time is usually tiny (well under a kilobyte, even though the full stack is usually several megabytes), so it’s likely to stick around in L1 cache. And return addresses on the stack get special treatment by the branch predictor. But other than that, it’s treated the same as any other memory.