Code Footprint

◀ Characteristics of a Good Program▶ Memory Footprint
Amazon Code size refers to the number of lines of a program. It’s also known as the code footprint of a program. In general, the lower the code size, the higher a program’s readability and efficiency, but it is not always the case.

For example, we discussed in Chapter 4 two types of functions that compute a Fibonacci number: recursive version and non-recursive version. The recursive version takes fewer lines of code than the non-recursive version; however, the time complexity of the recursive version is way out of sight.


There are several ways to reduce the code size of a program. One of the most effective ways is to understand the programming language thoroughly.

For example, the following statement, assuming a, b, c are initialized integers:

a = b < c ? 10 : 20;

is equivalent to

if (b < c) {
a = 10;
} else {
a = 20;
}

But if you do not know how ?: works, you cannot make this optimization.


There are plenty of other examples that illustrate the fact that knowing a language well can help you reduce code size. Here is another one. The following statement:

for_each(lottery.begin(), lottery.end(), drawLottery);

can replace
vector<int>::iterator vi;
for(vi = lottery.begin(); vi != lottery.end(); vi++) {
	drawLottery(*vi);
}
There are many functions provided by C++ standard libraries (C++ standard template library is covered by Chapter 7) that you can use to your advantage. You need to explore more in order to get a decent grasp of C++ libraries. By simply including the libraries in the header and calling appropriate functions in the body, you can reduce code size dramatically.


In addition, most functions in the standard library have gone through exhaustive testing and optimizing, so they are very robust and error resilient. If something goes wrong, they generally won’t make your program crash.
Other ways to reduce code size include reducing the number of functions (while keeping a healthy balance between number of functions and function code size), using fewer variables and data objects, figuring out a different technique to tackle the same problem, and so on.

An example of using a different technique is use a formula to calculate the sum of successive squares of integers (1^2+2^2+3^2+…+n^2) as opposed to doing it the procedural, verbatim way. Obviously this way only applies to tasks where you can apply a more efficient technique to solve, and it always helps to think whether such a technique exists in any given task!


Next let’s look at how low memory footprint contributes to a well written program!
◀ Characteristics of a Good Program▶ Memory Footprint

fShare
Questions? Let me know!