Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons to not pass simple types by reference?

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?

like image 250
Daniel Figueroa Avatar asked May 26 '12 23:05

Daniel Figueroa


People also ask

What are the disadvantages of using a reference?

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.

Is it better to pass by reference or value?

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.

When should you pass by reference?

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.

Why should you pass by reference?

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.


2 Answers

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.

like image 71
Ry- Avatar answered Oct 16 '22 16:10

Ry-


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.

like image 21
Mahmoud Al-Qudsi Avatar answered Oct 16 '22 16:10

Mahmoud Al-Qudsi