Aussie AI
Specialize functions with default arguments
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Specialize functions with default arguments
Every default function argument is a place where you can optimize. Default arguments to functions are not a source of inefficiency in themselves, and cost no more than using a fixed-argument function and passing some constants explicitly. However, the use of default arguments indicates the possibility of improving efficiency by replacing a single function with a number of specialized functions.
How to do this? Instead of one function with a default argument, create two functions using function overloading. The specialization of the function into two separate functions will often make other optimization techniques possible, thus improving overall efficiency at the cost of some duplication of executable code. As an example of the possibilities that can exist, consider the function with default arguments:
void indent(int n = 4) // default argument n=4 { for (int i = 0; i < n; i++) cout.put(’ ’); }
Rewriting this single function as one general function and one specialized function leads to opportunities for optimization in the specialized function. In this case, loop unrolling can be employed:
void indent() // Specialized function (n=4) { cout.put(’ ’); // Loop completely unrolled cout.put(’ ’); cout.put(’ ’); cout.put(’ ’); } void indent(int n) // General function { for (int i = 0; i < n; i++) cout.put(’ ’); }
Note that this optimization is also limited in scope,
as there any need to change any
other code that calls the functions.
The C++ compiler will automatically make the correct choice of which overloaded function to call.
Another thought for improved readability
is to name the specialized function differently (e.g., indent4
),
which requires calls to the function to be changed.
However, default arguments are certainly convenient and the slight increase in efficiency
should be balanced against the loss of good programming style.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |