Memory Footprint

◀ Code Footprint▶ Run-time efficiency of a Program
Amazon Memory footprint refers to the amount of memory used when a program is running. The less memory the program needs while running the better due to the following reasons:
  • The program may run faster because less memory usually implies less machine instructions.
  • The platform you are running the program on does not need too much physical memory.
  • It is less likely to crash the platform you are running the program on.
So how do we achieve smaller memory footprint in your program? Unfortunately you need intimate knowledge of how the compiler and the call stack work. You need to know how your C++ statement is translated into machine instructions.

In fact the compiler will first attempt to optimize the the C++ statements and then translate them into machine instructions.

The way the compiler does the optimization varies from system to system and from version to version. So it’s very strenuous and challenging to know exactly the memory footprint generated by the program during run time on the given platform.
That said don’t be discouraged. There are general rules and habits you should adopt to optimize memory footprint. Here are some of them:
  • Avoid using unnecessary pointers. Each pointer takes 4 bytes of memory. By avoiding using one pointer and using the variable or object directly you save 4 bytes of memory.
  • Avoid using statements that result in too many machine instructions. You can kind of use your common programming sense simply by running the program in your head. For example suppose your program has a big switch statement (or alternatively a series of if-else statements) which simply assigns a variable to some value given some condition. Imagine how many compare, call, jump instructions need to be created when the program is running! If you can use a map-like or hashtable-like data structure in C++ then you can create a static mapping between keys and values and be able to do this task with much fewer instructions and therefore smaller memory footprint!
  • Use as few variables as possible. If you inspect your program do you see that it uses multiple variables to track one piece of data or one state? For example if you use more than one variable to represent one state in your program then reconsider. You may be able to revise your code so that only one variable is used to represent one state. Each additional variable creates additional memory in the runtime of your program.
Next let’s look at the next property of a well written program – high efficiency.
◀ Code Footprint▶ Run-time efficiency of a Program

fShare
Questions? Let me know!