C++ pass by value / reference

Associate
Joined
25 Jul 2003
Posts
1,980
If I want to pass some primitive value (integer, double etc) to a function which will use the value (but not modify it), what is the most efficient method to pass it?
 
Just pass by value for primatives, the space occupied by pushing a copy onto the stack is negligable.

Pass by reference is usually less efficient than pass by value. You must dereference all pass by reference parameters on each access. This is slower than using a value since it typically requires at least two instructions.

Pass by reference for objects you need to modify. Only pass by const reference when the object is large or needs to maintain polymorphic behavour.

Code:
void test(int &x)
{
	int z = x + 2;
}

pass by reference:

int z = x + 2;
004113AE  mov         eax,dword ptr [x] 
004113B1  mov         ecx,dword ptr [eax] 
004113B3  add         ecx,2 
004113B6  mov         dword ptr [z],ecx

pass by value:

int z = x + 2;
004113AE  mov         eax,dword ptr [x] 
004113B1  add         eax,2 
004113B4  mov         dword ptr [z],eax

As you can see there is not a great deal in it though. I think you need to worry about your algorithms not this kinda micro-optimisation. :p
 
Last edited:
Back
Top Bottom