Efficient way to pass struct as parameter

Ali Çehreli acehreli at yahoo.com
Wed Jan 3 18:57:13 UTC 2018


On 01/03/2018 10:40 AM, Patrick Schluter wrote:
 > On Tuesday, 2 January 2018 at 23:27:22 UTC, H. S. Teoh wrote:
 >>
 >> When it comes to optimization, there are 3 rules: profile, profile,
 >> profile.  I used to heavily hand-"optimize" my code a lot (I come from
 >> a strong C/C++ background -- premature optimization seems to be a
 >> common malady among us in that crowd).
 >
 > That's why I always tell that C++ is premature optimization oriented
 > programming, aka as POOP.

In my earlier C++ days I've embarrassed myself by insisting that strings 
should be passed by reference for performance reasons. (No, I had not 
profiled.) Then I learned more and always returned vectors (and maps) by 
value from producer functions:

vector<int> makeInts(some param) {
     // ...
}

That's how it should be! :)

I used the same function when interviewing candidates (apologies to all; 
I don't remember good things about my interviewing other people; I hope 
I will never interview people like that anymore). They would invariably 
write a function something like this:

void makeInts(vector<int> & result, some param) {
     // ...
}

And that's wrong because there are the big questions of what do you 
require or do with the reference parameter 'result'? Would you clear it 
first? If not, shouldn't the function be named appendInts? If you 
cleared it upfront, would you still be happy if an exception was thrown 
inside the function, etc.

That's why I like producer functions that return values:

vector<int> makeInts(some param) {
     // ...
}

And if they can be 'pure', D allows them to be used to initialize 
immutable variables as well. Pretty cool! :)

Ali



More information about the Digitalmars-d-learn mailing list