Passing an object by reference is an easier, faster and safer way to pass an address to it.
But for most compilers, it’s all the same: references are really pointers.
Now what about basic types like int? Passing an address to an int and using it inside a function would be slower than passing it by copy, because the pointer needs to be dereferenced before use.
How do modern compiler handle, this?
int foo(const int & i)
{
cout << i; // Do whatever read-only with i.
}
May I trust them to compile this into this?
int foo(const int i)
{
cout << i;
}
By the way, in some cases it could even be faster to pass both i and &i, then use i for reading, and *i for writing.
int foo(const int i, int * ptr_i)
{
cout << i; // no dereferencement, therefore faster (?)
// many more read-only operations with i.
*ptr_i = 123;
}
Visual Studio 2010 (Express) does, in the simple cases I’ve tested at least. Anyone to test gcc?
I’ve tested the following:
1. Passing only
i:The ASM:
Well, the ASMs are identical, no doubt the optimization was performed.
2. Passing
iand&i:Let’s consider @newacct ‘s anser here.
The ASM:
In
ok1I can’t see it writing 2 intopi. Probably it understands that the memory location will be overwritten by the result of the function anyway, so the writing is useless.With
ok2, the compiler is as smart-ass as I expected. It understands thatiandpipoint to the same place, so it uses a hardcoded2directly.Notes:
ok1, once uncommenting onlyok2. Compiling both at the same time leads to more complex optimizations between the two functions, which end up all inlined and mixed upvarsbecause simple calls tosqrtlwere simplified into basic ADD- and MUL-like operations without the actual call