Reputation: 10676
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?
Upvotes: 9
Views: 5435
Reputation: 29579
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.
Upvotes: 4
Reputation: 225125
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.
Upvotes: 10
Reputation: 2558
For example, in 32 bit mode, int
size is 4 bytes and int *
pointer size is 4 bytes.
Passing 4 bytes int
directly is quicker, than passing 4 byte pointer and then loading int
by that pointer.
Upvotes: 0
Reputation: 4992
Internally references are treated at pointers, which need to be dereferenced each time you access them. That obviously requires additional operations.
Upvotes: 0