I've just written a recursive function and it dawned on me that all the variables I use within the function will remain allocated in memory until recursion breaks. If I am recursing a large number of times or allocating large amounts of memory for variables not used in the consequent recursive function call, could this lead to alot of wasteful memory use?
E.g. in the following, only vec2
is used in the following recurse and temp_int
and temp_vec
will continue to occupy memory needlessly.
int recurse(std::vector<int> arg_vec) {
int temp_int i;
std::vector<int> temp_vec;
std::vector<int> vec2;
//... do some processing with arg_vec and temp_vec and result is stored in vec2
recurse(vec2)
return if (some condition met);
}
Should I then be allocating all memory using the new commands and deleting them before the function call? Or is there some other method for dealing with this
Bottom-up. Sometimes the best way to improve the efficiency of a recursive algorithm is to not use recursion at all. In the case of generating Fibonacci numbers, an iterative technique called the bottom-up approach can save us both time and space.
Recursion uses more memory. Because the function has to add to the stack with each recursive call and keep the values there until the call is finished, the memory allocation is greater than that of an iterative function.
From the previous example, we can see that recursive calls in co or async functions may delay the memory deallocation. This delay leads to memory pileups and memory pressure.
Recursive algorithms are often inefficient for small data, due to the overhead of repeated function calls and returns. For this reason efficient implementations of recursive algorithms often start with the recursive algorithm, but then switch to a different algorithm when the input becomes small.
You can use scope braces to specify a scope. Anything declared in a scope is destroyed at the end of the scope.
int recurse(std::vector<int> arg_vec) {
int temp_int i;
std::vector<int> vec2;
{
std::vector<int> temp_vec;
//... do some processing with arg_vec and temp_vec and result is stored in vec2
} // temp_vec is destructed here. vec2 is not because it is outside this scope.
recurse(ec2)
return if (some condition met);
}
Typically, what you do in this situation is tail-recursion, which allows the compiler to optimise just that.
That means, the last thing your recursive function does is calling itself. I am not aware how good the optimisation is if you have further instructions.
Edit (clarification)
int foo(int i) {
if (stop_condition(i))
return stuff;
// fancy computation
return foo(bar);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With