Is `alias this` a mistake?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Aug 5 17:44:48 UTC 2021


On Thu, Aug 05, 2021 at 05:24:56PM +0000, IGotD- via Digitalmars-d wrote:
[...]
> I never understood the benefit of structs are value types. In what use
> case would you like to pass the value of a struct rather than a
> reference. The struct will be copied on the stack which is inefficient
> so in 99% of the cases you would like to use the reference, especially
> when the parameter is const. If you need a copy the called function
> could be responsible for that.
> 
> Could someone explain the benefit of this "glorified int".

I think your assumption that passing on the stack is inefficient is not
necessarily correct.

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 heap.  Furthermore,
if your struct is small enough, it can be passed entirely in CPU
registers, which is much faster than any heap-allocated object can ever
hope to be.  (And if your struct is too large, esp. if it's so large the
compiler has to resort to passing a reference under the hood, you
probably should be using a class in the first place.)

Also, a stack-allocated object has a well-defined lifetime that's
trivially known to the optimizer, so in many cases good optimizing
compilers like LDC can entirely elide the stack allocation and keep the
struct in registers for its entire lifetime.  It's much harder for the
optimizer to figure out the lifetime of a heap-allocated object, so it
would conservatively skip such optimizations.

If performance is important to you, one of the first things you should
be looking at is reducing heap usage where possible -- memory management
is expensive, whether you use GC or some other method of memory
management. Stack allocation is the best because deallocation comes "for
free" when the function returns. Using structs instead of classes is a
powerful tool for this purpose.


T

-- 
Маленькие детки - маленькие бедки.


More information about the Digitalmars-d mailing list