Is making smaller functions generally more efficient memory-wise since variables get deallocated more frequently? [closed]
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 q开发者_StackOverflowuestion, only in respect to memory usage.
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.
So here's my philosophy. I think that, unless you're doing some crazy scientific computation that will call several different functions several millions of times (and thus overburden the system stack and lead to stackoverflow), you're good to go to break up your code (obviously don't go too crazy). But breaking up code, especially in OO code, is a godsend (especially for debugging and readability). In the end, it's all about trade offs.
Actually, now that I think of it, if you have a considerable amount of variables and the stack comes from a centralized main, most people will thread their application/program accordingly.
Since I'm not sure where you're coming from, if you're very conscious about efficiency, take a look at this question and its answers (pertaining to low level code):
How to write fast (low level) code?
If you're actually/literally talking about this enveloping all the languages you tagged, despite them all being C-based languages, they actually have very different memory/memarch models (especially since Java runs on the VM).
精彩评论