Search code examples
ccompiler-constructionprogramming-languages

Is making smaller functions generally more efficient memory-wise since variables get deallocated more frequently?


Is dividing the work into 5 functions as opposed to one big function more memory efficient in C since at a given time there are fewer variables in memory, as the stack-frame gets deallocated more often?

Answer given there are a lot of local variables and the stack frames comes from a centralized main and not created on the top of each other.

I know other advantages of breaking out the function into smaller functions. Please answer this question, only in respect to memory usage.


Solution

  • It's very language and compiler dependent.
    For languages like Python where variables can be accessed dynamically (eg globals()['x']), you're effectively reducing the time for which each variable is in an accessible scope, allowing the memory to be reclaimed more often. Depending on how you do it, you may be forcing the interpreter to hold on to more scopes, and the scopes themselves can potentially use extra memory. Eg, if you're taking a chunk out of f1 and making it f2 which gets called from f1, you're increasing the stack depth & the number of scopes that have to be held onto.

    For compiled languages with mature compilers like C, the memory for variables is often only used for as long as they are actually needed. So you won't be able to do much that the compiler doesn't already do.

    Keep in mind that when you call a function, local variables need to be moved from registers onto the stack, as well as a return address. So in some cases, you'll end up with a bigger memory footprint if you break it apart into multiple functions called from within the original.
    But also realize that if a function is only called from one place, there's a good chance that your compiler will inline it.

    So in summary, it's hard to predict, and will make very little difference. Just do what is most readable.