Taking arguments by value or by reference

IGotD- nise at nise.com
Sun Oct 4 15:30:48 UTC 2020

On Saturday, 3 October 2020 at 23:00:46 UTC, Anonymouse wrote:
> I'm passing structs around (collections of strings) whose 
> .sizeof returns 432.
> The readme for 2.094.0 includes the following:
>> This release reworks the meaning of in to properly support all 
>> those use cases. in parameters will now be passed by reference 
>> when optimal, [...]
>> * Otherwise, if the type's size requires it, it will be passed 
>> by reference.
>> Currently, types which are over twice the machine word size 
>> will be passed by
>> reference, however this is controlled by the backend and can 
>> be changed based
>> on the platform's ABI.
> However, I asked in #d a while ago and was told to always pass 
> by value until it breaks, and only then resort to ref.
>> [18:32:16] <zorael> at what point should I start passing my 
>> structs by ref rather than by value? some are nested in 
>> others, so sizeofs range between 120 and 620UL
>> [18:33:43] <Herringway> when you start getting stack overflows
>> [18:39:09] <zorael> so if I don't need ref for the references, 
>> there's no inherent merit to it unless I get in trouble 
>> without it?
>> [18:39:20] <Herringway> pretty much
>> [18:40:16] <Herringway> in many cases the copying is merely 
>> theoretical and doesn't actually happen when optimized
> I've so far just been using const parameters. What should I be 
> using?

I don't agree with this, especially if the struct is 432 bytes. 
It takes time and memory to copy such structure. I always use 
"const ref" when I pass structures because that's only a pointer. 
Classes are references by themselves so its not applicable there. 
Only "ref" when I want to modify the contents.

However there are some exceptions to this rule in D as D support 
slice parameters. In this case you want a copy as slice of the 
array, often because the slice is often casted from something 
else. Basically the array slice parameter become an lvalue.

This copy of parameters to the stack is an abomination in 
computer science and only useful in some cases but mostly not. 
The best would be if the compiler itself could determine what is 
the most efficient. Nim does this and it was not long ago 
suggested that the "in" keyword should have a new life as such 
optimization, is that the change that has entered in 2.094.0? Why 
wasn't this a DIP?

I even see this in some C++ program code where strings are passed 
as value which means that the string is copied including a 
possible memory allocation which certainly slow things down.

Do not listen to people who says "pass everything by value" 
because that is in general not ideal in imperative languages.

More information about the Digitalmars-d-learn mailing list