Is there anything to be gained by using const int &var
formal parameters in place of const int var
?
I know the advantage in large structs but for PODs the pointer is often of equal size to the actual 开发者_StackOverflow社区data. So I guess the answer would be "No advantage". But I think perhaps the pass by value semantics copies once to the stack and again to an area off the stack for easier reference (say to a register). Or maybe not. In fact it may infact be better to pass by value,
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Because references are typically implemented by C++ using pointers, and dereferencing a pointer is slower than accessing it directly, accessing values passed by reference is slower than accessing values passed by value.
But this gets back to what I was saying about copying back off the stack. I'm just being paranoid right? This behaviour is for the compiler to worry about and not me.
I could single step the assembly I know, but, well, googling is faster and it came up blank.
Consider this:
Non-reference
- Allocate an int on the stack
- Copy the value to the stack
- Call the function like usual
- Use the variable on the stack
Reference
- Allocate a pointer on the stack
- Copy address of int to stack
- Call the function like usual
- Dereference the variable on the stack (possibly multiple times in the same function)
- Use the variable
It's slightly slower to use the reference version. Generally though, let the compiler worry about it. If it's a read-only value, just give it a regular old int. If you need to modify the caller's value, use a reference or a pointer.
Of course that's only true for a small data type like an int. If you were talking about something bigger like a struct or something it would probably be faster to use a reference.
When you pass a reference you copy the value of the reference, all the same. When you use it, you waste a few cycles on indirection, but other than that there is no performance difference.
Of course, there could be a difference in program behaviour, if you cast away constness, or if you change the referenced value on a different thread.
精彩评论