Sams Teach Yourself C++ in 21 Days

(singke) #1

Inline Functions ..............................................................................................


When you define a function, normally the compiler creates just one set of instructions in
memory. When you call the function, execution of the program jumps to those instruc-
tions, and when the function returns, execution jumps back to the next line in the calling
function. If you call the function 10 times, your program jumps to the same set of
instructions each time. This means only one copy of the function exists, not 10.
A small performance overhead occurs in jumping in and out of functions. It turns out
that some functions are very small, just a line or two of code, and an efficiency might be
gained if the program can avoid making these jumps just to execute one or two instruc-
tions. When programmers speak of efficiency, they usually mean speed; the program runs
faster if the function call can be avoided.
If a function is declared with the keywordinline, the compiler does not create a real
function; it copies the code from the inline function directly into the calling function. No
jump is made; it is just as if you had written the statements of the function right into the
calling function.
Note that inline functions can bring a heavy cost. If the function is called 10 times, the
inline code is copied into the calling functions each of those 10 times. The tiny improve-
ment in speed you might achieve might be more than swamped by the increase in size of
the executable program, which might in fact actually slow the program!
The reality is that today’s optimizing compilers can almost certainly do a better job of
making this decision than you can; and so it is generally a good idea not to declare a
function inline unless it is only one or at most two statements in length. When in doubt,
though, leave inlineout.

122 Day 5


Performance optimization is a difficult challenge, and most programmers
are not good at identifying the location of performance problems in their
programs without help. Help, in this case, involves specialized programs like
debuggers and profilers.
Also, it is always better to write code that is clear and understandable than
to write code that contains your guess about what will run fast or slow, but
is harder to understand. This is because it is easier to make understandable
code run faster.

NOTE

Listing 5.9 demonstrates an inline function.
Free download pdf