Is `alias this` a mistake?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Aug 6 14:18:30 UTC 2021


On Fri, Aug 06, 2021 at 12:27:55PM +0000, wjoe via Digitalmars-d wrote:
> On Thursday, 5 August 2021 at 17:44:48 UTC, H. S. Teoh wrote:
[...]
> > Since the stack is almost constantly being accessed in the course of
> > a program's execution, it remains in cache and so is much more
> > cache-friendly than dereferencing a pointer to the
> 
> This raises the question how does this apply to a CPU that has a L1
> cache of 512KiB, a L3 of 4MiB for a program with a stack size of 8MiB
> ?

The stack is called the stack, precisely because you generally only
access it at the top (or near the top). You generally do not access
random parts of it, esp. not the parts near the bottom; most accesses
are expected to be near the top.  That's the area of the stack that
would tend to be in the cache.


> As far as I'm aware stack memory is residing on the heap so it will
> need to be allocated on program start up.

I think you're confusing the terminology here.  "Stack" refers to an
area of a program's memory that the OS allocates specifically to be used
as the runtime stack, the usage pattern of which is expected to be FIFO
(first-in, first-out). The "heap" is an additional area (or areas,
depending on the implementation of a language's runtime) designated for
non-FIFO, ad hoc memory allocation (malloc/free, GC, etc.).

In modern OSes, the stack is mapped to its own range of addresses in the
program's address space, which, depending on OS settings, may grow as
program recursion level increases.


> So in theory...
> if we were pre-allocating a chunk of memory on the heap at program
> startup and used that to store our data (like on a stack), the cost of
> allocation would have been paid, once we need to use it, and would
> only have to be done once. "Deallocation" cost for data using this
> "stack" should be getting pretty close to that of *the* stack (which
> is basically a subtraction).  Deallocation cost for the block of heap
> memory on program termination doesn't matter.
[...]

That's missing my point.  My point was that the runtime stack is
cache-friendly because it's always "hot": the program is practically
constantly accessing it: every function call, every `return`, every
access of local variables touch the stack, so it practically never
leaves the cache.  Whereas a user-allocated stack on the heap may be
evicted from the cache if it hasn't been accessed in a while.


T

-- 
What's a "hot crossed bun"? An angry rabbit.


More information about the Digitalmars-d mailing list