0

Recursive functions or loop operators, which is faster or memory saving or both?

Cycle operations

1st Mar 2019, 4:13 PM
Emrys
Emrys - avatar
7 odpowiedzi
+ 2
Loops should be more efficient than recursion. The reason: - everytime a function is called, the parameters have to be saved on the stack before the function can be called - when a function is called local variables have to be created on the stack - when the function returns, the return value has to be put on the stack - after a function call evaluate the return value If you can programm everything in a loop, you will save a lot of variable creation and function calling.
1st Mar 2019, 6:47 PM
nobody
0
What if it's not C++, what about Java or something like Javascript?, does it do the same thing?
1st Mar 2019, 9:18 PM
Emrys
Emrys - avatar
0
In addition to that I think loops creates variables too and it's probably done on the stack memory.
2nd Mar 2019, 4:41 AM
Emrys
Emrys - avatar
0
#include <iostream> using namespace std; int main() { int i, num1, num2, sum = 0; num1 = 3; num2 = 7; for(i = num1; i <= num2; i++) { sum += i; cout << "This i = " << i << " and sum = " << sum << endl; } cout << "This i = " << i << " and sum = " << sum << endl; return 0; } I think I've found out something, in the above code the output is: This i = 3 and sum = 3, This i = 4 and sum = 7, This i = 5 and sum = 12, This i = 6 and sum = 18, This i = 7 and sum = 25, and after exiting the loop operation, This i = 8 and sum = 25. This indicates that variables instantiated during operation still exists while in recursive functions they are deleted after function termination.
5th Mar 2019, 10:48 AM
Emrys
Emrys - avatar
0
So just put Int i Info the for end it will gone after the loop. And you can scope the other variables. But that's not what I meant!
5th Mar 2019, 4:17 PM
nobody
0
Now I get it, scope resolution stuff, int i is still withing the scope of the output
5th Mar 2019, 4:52 PM
Emrys
Emrys - avatar
0
But that doesn't mean it's being deleted, now see this code in Javascript: var i, num1, num2, sum = 0; num1 = 3; num2 = 7; for(i = num1; i <= num2; i++) { var intValue = i + (i * 2); sum += i; document.write("This i = " + i + " and sum = " + sum + "<br />"); } document.write("This i = " + i + " and sum = " + sum + "<br />" + "intValue variable from loop operation = " + intValue + "<br />"); the thing is that it is obviously seen that in C++ any part of an expression/group of statements scope can be delimited withing braces { } in Javascript the variable is still accessed, the code will still be experimented in Java program and I'll get back to you.
5th Mar 2019, 5:10 PM
Emrys
Emrys - avatar