In recursive scenarios, what brings more performance? Doing 3-4 simple calculations once, store result on a variable and then use variable maximum 3-4 times in each recursive function call? Or to skip saving result on a variable and just do the 3-4 math operations each of the 3-4 times needed? What bugs me with variable is that since the function is recursive, each 4-byte variable will be stored in stack until the function returns and that may add up a lot. I don't know how much big of a deal it is to allocate memory for an integer and store a value in there, but it does sound like it is something. i.e. Scenario 1: int a = w + x - y / z; use a; use a; use a; use a; vs Scenario 2: use w + x - y / z; use w + x - y / z; use w + x - y / z; use w + x - y / z;

Thanks in advance.


Like almost everything in the programming, the use of recursion must be made in appropriate cases, you are right regarding the excessive memory usage, and the successive return statements are pending evaluating until the base case, which can be inefficient . However we can not exclude recursivity completely, in many cases the code for an iterative program may be too complex, recursive solution can be as efficient and be more elegant and simple. You can try writing an iterative program to calculate the power of a number, even something a bit more complicated as Fibonacci series, in these cases you can see the advantage of using recursivity

  • I think I am gonna download the .c files I wrote and maybe a fibonacci impementation and compile them on a raspberry pi running headless raspbian lite and "benchmark" both ways(iterative and recursive). There is no point doing that on the cloud IDE. I believe that the results will save me time in future projects when trying to decide which method to use. Thank you for your reply. – Alexandros Tsiapas Aug 14 '16 at 13:34
  • 1
    You will probably have to run both cases at least a thousand times to see any noticeable differences in time, since this math operation is pretty lightweight. In any case, like many times in programming, you have to balance memory and CPU work and see which will give you the best results for your case. – ChrisG Aug 15 '16 at 13:40
  • I was thinking more in the code than in time – MARS Aug 16 '16 at 13:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .