Memory Footprint of a Function
◀ Efficiency of a Function▶ Reliability of a Function Amazon
Memory footprint refers to the amount of memory used when a function is running. The less memory the function needs while running the better due to the following reasons:
- The function may run faster because less memory usually implies less machine instructions.
- The platform you are running the function on does not need too much physical memory.
- It is less likely to crash the platform you are running the function on.
So how do we achieve smaller memory footprint in your function?
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 function 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 function in your head. For example suppose your function 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 function 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 function 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 function.
Next let’s look at the next property of a well written function - high reliability.
◀ Efficiency of a Function▶ Reliability of a Function