r/cpp • u/ReDucTor Game Developer | quiz.cpp-perf.com • Jun 27 '22
Pass-by-value vs Pass-by-reference
https://reductor.dev/cpp/2022/06/27/pass-by-value-vs-pass-by-reference.html2
u/dr-mrl Jun 27 '22
Now letβs see how these value types impact
thewhat happens before and after the call
Typo OP?
1
u/ReDucTor Game Developer | quiz.cpp-perf.com Jun 27 '22
thanks for pointing that out, i have just updated it
2
u/0xE6 Jun 27 '22
I get a 404 when I try to visit
https://reductor.dev/cpp/2022/06/27/pass-by-value-vs-pass-by-reference.html
Did something change?
3
u/ReDucTor Game Developer | quiz.cpp-perf.com Jun 27 '22
God damn github pages, breaking things
As soon as I push changes seems to break the custom domain stuff
1
9
2
u/wqking github.com/wqking Jun 28 '22
Good article. I like the tables very much, they are very informative.
1
u/fdwr fdwr@github π Jun 30 '22 edited Jun 30 '22
I see you're in the camp 4% :b. https://www.reddit.com/r/cpp/comments/vm8bwm/how_do_you_declare_pointer_variables/
π€ This __vectorcall is interesting as I've never used it (but I do dabble in graphics/ML often).
The deducing this addition interestingly brings this byval vs byref question to method calls now too.
0
Jun 27 '22
[deleted]
2
u/ReDucTor Game Developer | quiz.cpp-perf.com Jun 27 '22
That tl;dr doesn't really represent the post, sometimes copies are good, also just focusing avoiding copies you have room for more aliasing.
Unless you know all your usecases, it's not really that its not worth attempting to define a set of rules, instead if performance is important profile your code and take action based on that.
I probably should also highlight that if your calling conventions are impacting the performance somewhere it might be one of the rare cases that force inline is worth doing.
9
u/NilacTheGrim Jun 27 '22
And you'd be surprised what is faster by value and what is faster by reference. I have seen cases where short strings passed by value, that take advantage of the short-string optimization ended up producing faster code than passing
const std::string &in some cases. You'd naively think that all strings are always faster if passed-in by reference but ... not always!Often if the object itself is just a handful of machine words in size (say up to 32 bytes) it may be faster just to push a copy of it onto the stack and have it "there" very local to all the other variables and thus very likely to be in the fastest level of cache.
Naively you'd think that passing an 8-byte pointer to a 32-byte thing is surely always faster than copying a 32-byte thing.. but not always!
The moral of the story is -- benchmark, benchmark, benchmark!
5
u/jk-jeon Jun 27 '22 edited Jun 27 '22
FYI. Code snippets in the first table is not correctly formatted in my browser.
Edit: After reading it. I love this article. Thanks!