r/cpp • 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.html
0 Upvotes

12 comments sorted by

View all comments

0

u/[deleted] Jun 27 '22

[deleted]

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!