I tend to use const reference
parameters when calling functions assuming this would be efficient since copies of the same wouldn't not be made. Accidentally I changed the function parameter in a function that previously had a const reference
parameter to const
now, and I observed that the code size is reduced upon compilation.
To check this, I looked into the assembly of a MWE :
#include <cstdint>
void foo(const int n)
{
int a = n + 1;
}
void foo(const int& n)
{
int a = n + 1;
}
On line 19 of the generated assembly code, I see an additional step ldr r3, [r3]
in the case of void foo(const int& n)
when compared to void foo(const int n)
. I assume this is the reference to variable n
(I could be wrong, please forgive me).
So, my question is, why is the code larger when passing via reference and also what method is efficient?
A reference can be understood as something in between a name alias and a pointer. From What are the differences between a pointer variable and a reference variable? :
A compiler keeps "references" to variables, associating a name with a memory address. Its job is to translate any variable name to a memory address when compiling. When you create a reference, you only tell the compiler that you assign another name to the pointer variable; that's why references cannot "point to null". A variable cannot be, and not be at the same time. Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.
On a 32 bit-machine, a pointer
has 4 bytes ( 4*8 = 32
bits) while on a 64-bit machine a pointer
has 8 bytes ( 8*8 = 64
bits), because that is the size of a single memory address.
On a 32 bit-machine, int
, long
are each 4 bytes (32 bits) quantities. On most 64-bit systems, long
becomes 8 bytes (64 bits), but int
remains 32-bit (4 bytes).
[Speaking about primitive types, the size of char
is fixed at 1 byte (or CHAR_BIT = 8
bits) explicitly in the C++ standard.]
Given that passing a const reference
as function parameter requires the compiler to dig for the memory address of the referenced variable, in case the variable is a primitive type such as int
or char
the digging in memory ( pointer
is 8 bytes) is going to be more expensive than passing the variable itself by value (4 bytes for int
, 1 byte for char
).
The question is about the efficiency of parameters passed by const reference
. Of course, a function accepting a parameter by non-const reference
would have the advantage - unrelated to efficiency - of allowing modifications of the referenced variable to persist, when control goes back to the caller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.