Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass reference to output location vs using return

Which is better for performance when calling a function that provides a simple datatype -- having it fill in a memory location (passed by pointer) or having it return the simple data?

I've oversimplified the example returning a static value of 5 here, but assume the lookup/functionality that determines the return value would be dynamic in real life...

Conventional logic would tell me the first approach is quicker since we are operating by reference instead of having to return a copy as in the 2nd approach... But, I'd like others' opinions.

Thanks

void func(int *a) { *a = 5; }

or...

int func() { return 5; }

like image 688
Paul Avatar asked Mar 06 '11 19:03

Paul


People also ask

Which is generally more efficient a function that returns an object by reference or a function that returns an object by value?

Returning the object should be used in most cases because of an optimsation called copy elision. However, depending on how your function is intended to be used, it may be better to pass the object by reference.

Which is better pass by value or pass by reference?

Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.

What is an advantage of passing parameters by value as opposed to passing them by reference?

Pass by value - The function copies the variable and works with a copy (so it doesn't change anything in the original variable) Pass by reference - The function uses the original variable. If you change the variable in the other function, it changes in the original variable too.

What is the correct way to pass a parameter by reference?

Pass by reference (also called pass by address) means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function so that a copy of the address of the actual parameter is made in memory, i.e. the caller and the callee use the same variable for the parameter.


1 Answers

In general, if your function acts like a function (that is, returning a single logical value), then it's probably best to use int func(). Even if the return value is a complex C++ object, there's a common optimisation called Return Value Optimisation that avoids unnecessary object copying and makes the two forms roughly equivalent in runtime performance.

like image 129
Greg Hewgill Avatar answered Sep 26 '22 18:09

Greg Hewgill