Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing scalar types by value or reference: does it matter?

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?

like image 357
Jonathan H Avatar asked Jan 07 '14 21:01

Jonathan H


People also ask

What is the difference between pass by reference and pass by value?

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.

What happens when you pass a parameter to a function by reference?

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.

Is Python’s argument passing model “pass by value or pass by reference”?

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.

What happens when you pass a variable to a function?

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.


1 Answers

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.

like image 125
Mgetz Avatar answered Oct 28 '22 23:10

Mgetz