jeffc said:
Can anyone point me to a web site that gives technical reasons that pass by
value is preferred over pass by reference when the value is not to be
changed? Actually it could be any built-in "small" type (short, bool, etc.)
Let's see:
int pass_by_reference( int & a, int & b )
{
return a + b;
}
int pass_by_value( int a, int b )
{
return a + b;
}
passing_params.o: file format elf32-i386
Disassembly of section .text:
00000000 <_Z17pass_by_referenceRiS_>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 0c mov 0xc(%ebp),%eax
6: 8b 00 mov (%eax),%eax
8: 8b 55 08 mov 0x8(%ebp),%edx
b: 03 02 add (%edx),%eax
d: c9 leave
e: c3 ret
f: 90 nop
00000010 <_Z13pass_by_valueii>:
10: 55 push %ebp
11: 89 e5 mov %esp,%ebp
13: 8b 45 0c mov 0xc(%ebp),%eax
16: 03 45 08 add 0x8(%ebp),%eax
19: c9 leave
1a: c3 ret
Which one do you think is faster ?
Try a passing parameters in registers calling convention (SPARC).
_Z17pass_by_referenceRiS_:
ld [%o0], %g1
ld [%o1], %o2
retl
add %g1, %o2, %o0
_Z13pass_by_valueii:
retl
add %o0, %o1, %o0
Now which one do you think is faster ?
The true answer is - it depends. A simple function like these are
easily candidates for inlining - however if these are not inlineable
then passing somthing that can reside in a register by value rather than
by reference can have performance gains due to not needing to
dereference. Also, it depends on the circumstances of the caller, if
the caller does not have the values in registers it may be less
expensive computationally to pass the pointers instead of dereferencing
in the caller.
The common wisdom however is - the fewer instructions, the faster the
code. The correct thing to do is to though is benchmark your code. In
very few circumstances will this really make a difference.