Granted, micro-optimization is stupid and probably the cause of many mistakes in practice. Be that as it may, I have seen many people do the following:
void function( const double& x ) {}
instead of:
void function( double x ) {}
because it was supposedly "more efficient". Say that function
is called ridiculously often in a program, millions of times; does this sort of "optimisation" matter at all?
To summarise, in pass by reference the function and the caller use the same variable and object. In pass by value the function is provided with a copy of the argument object passed to it by the caller. That means the original object stays intact and all changes made are to a copy of the same and stored at different memory locations.
On the other hand, when you pass a value-type parameter to a function by reference, the changes you make to that parameter inside the function will change the original data.
You might want to punch something after reading ahead, so brace yourself. Python’s argument passing model is neither “Pass by Value” nor “Pass by Reference” but it is “Pass by Object Reference”. The paradigms of “Pass by value”, “Pass by Reference” and “Pass by object Reference” can be understood by exploring the below example functions.
When you pass by reference, you are passing the memory location of the variable to the function, and any changes you make inside a function will affect that location in memory and will therefore persist after the function completes. A couple of examples of reference types are Arrays and Delegates.
Long story short no, and particularly not on most modern platforms where scalar and even floating point types are passed via register. The general rule of thumb I've seen bandied about is 128bytes as the dividing line between when you should just pass by value and pass by reference.
Given the fact that the data is already stored in a register you're actually slowing things down by requiring the processor to go out to cache/memory to get the data. That could be a huge hit depending on if the cache line the data is in is invalid.
At the end of the day it really depends on what the platform ABI and calling convention is. Most modern compilers will even use registers to pass data structures if they will fit (e.g. a struct of two shorts etc.) when optimization is turned up.
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