CleanCode logo
sitemap
SEARCH:
NAVIGATION: first page in sectionprevious pageup one levelnext pagefinal page in section

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.

EXAMPLEJava, JavaScript
Instead of:
	print(string1); print(string2); print(string3);
Use:
	print(string1 + string2 + string3);
EXAMPLEPerl
Instead of:
	print($string1); print($string2); print($string3);
Use:
	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.

EXAMPLEJava, JavaScript
Instead of:
	statementA;
	statementB;
	print("text 1");
	print("text 2");
	print("text 3");
	print("text 4");
	print("text 5");
	statementC;
	statementD;
Use:
	statementA;
	statementB;
	print(
		"text 1" +
		"text 2" +
		"text 3" +
		"text 4" +
		"text 5"
	);
	statementC;
	statementD;
Valid XHTML 1.0!Valid CSS!Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads
Copyright © 2001-2013 Michael Sorens • Contact usPrivacy Policy
Usage governed by Mozilla Public License 1.1 and CleanCode Courtesy License
CleanCode -- The Website for Clean DesignRevised 2013.06.30