Guideline FN1: minimize function calls
Sometimes it is actually better to have more function calls
(see RP2,
RP3,
and RP4).
Sometimes it is better to have less function calls, as we'll discuss here.
It is cheaper to call a function once with a long argument rather than multiple times with short arguments.
By "cheaper", I mean that it requires less machine cycles to execute.
The classic case of this is the beguiling print
statement,
which can be viewed as a pure associative function.
Since each function call incurs overhead (typically allocating stack space,
storing arguments, calling the function, storing the return value, returning,
using the return value, and de-allocating stack space), it is faster
to do one function call where possible.
print(string1); print(string2); print(string3);
print(string1 + string2 + string3);
print($string1); print($string2); print($string3);
print($string1 . $string2 . $string3)
Consolidating multiple calls into one can also provide cleaner code by visually acting like a block of code. In the example below, the initial code shows a series of related print statements between other statements, but not set off visually in any way. The revised code reduces overhead by having just one print statement, plus sets off the arguments as a pseudo-block of code.
statementA; statementB; print("text 1"); print("text 2"); print("text 3"); print("text 4"); print("text 5"); statementC; statementD;
statementA; statementB; print( "text 1" + "text 2" + "text 3" + "text 4" + "text 5" ); statementC; statementD;