So far as I understand you should not pass simple types by reference in c++ because it does not improve perfomance, it's even bad for performance(?). At least thats what I managed to gather from the net.
But I can't find out the reason why it's bad for performance, is it because it's quicker for c++ to just create a new simple type than it it is too look up variable or what is it?
References can lie. You could get false information that disqualifies someone who actually would have been a good hire. Or you could get a glowing recommendation for someone that is not true. References can be inaccurate even if it's not an intentional lie.
Use pass by value when when you are only "using" the parameter for some computation, not changing it for the client program. In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.
Use pass-by-reference if you want to modify the argument value in the calling function. Otherwise, use pass-by-value to pass arguments. The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot.
Passing Large-Sized Arguments If an argument is significant in size (like a string that's a list), it makes more sense to use pass by reference to avoid having to move the entire string. Effectively, pass by reference will pass just the address of the argument and not the argument itself.
If you create a reference, it's:
pointer to memory location -> memory location
If you use a value, it's:
memory location
Since a value has to be copied either way (the reference or the value), passing by reference does not improve performance; one extra lookup has to be made. So it theoretically "worsens" performance, but not by any amount you'll ever notice.
It's a good question and the fact that you're asking it shows that you're paying attention to your code. However, the good news is that in this particular case, there's an easy way out.
This excellent article by Dave Abrahms answers all your questions and then some: Want Speed? Pass by Value.
Honestly, it does not do the link justice to summarize it, it's a real must-read. However, to make a long story short, your compiler is smart enough to do it correctly and if you try doing it manually, you may prevent your compiler from doing certain optimizations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With