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

Provided, micro-optimization is stupid and probably the cause of many errors in practice. Be that as it may, I have seen many people do the following:

void function( const double& x ) {}

instead:

void function( double x ) {}

because it was supposedly "more effective." Let's say what functionis called funny often in the program, millions of times; Is this "optimization" at all?

+3
source share
4 answers

, , , . , , 128 , .

, , , / . , , , .

, , ABI . , (, ..), .

+5

4B . 8B 4B ( 32b, 64b 64b = 8B, ) , , .

+2

, ( , , *), , :

  • double: () 8 .
  • double & double *: - ( "" , , , - ). A () 4 8 (32- 64- ) , strong > . , , .

, , , . , . .

, (, sizeof(T) > 32 , , ). , , , sizeof(T) > sizeof(T*).


*) . SOReader , , .

+2

, , . , const , . , , ( , , const_cast, const). , , , [] .

,

void function( const double& x ) {
  double non_aliased_x = x;
  // ... and use `non_aliased_x` from now on
  ...
}

, .

Another way to deal with an alias is to use some sort of classifier restrictin the style of C99

void function( const double& restrict x ) {

but then again, even in this case, the cons of following the link are likely to outweigh the pros, as explained in other answers.

+2
source

All Articles