Python Forum
Why recursive function consumes more of processing time than loops?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why recursive function consumes more of processing time than loops?
#9
This is why using recursion shouldn't be taken for granted. The use of resources can easily become exponential; and the more resources are used per function call, the worse it'll be.

While recursion can provide a simpler and more readable solution to a problem, you'll be able to achieve similar results if you use the right tools. For instance, this code:

def fib(n):
    fibs = []
    for i in range(n + 1):
        if i < 2:
            fibs.append(i)
        else:
            fibs.append(fibs[i - 2] + fibs[i - 1])
    return fibs[-1] if n >= 0 else 0
Provides the same simple solution by making use of a list to save and use the results as we iterate from 0 to n (included). The memory footprint in this case is minimal (only one function call and a list), as we don't take additional steps to keep track of n-1 and n-2 in order to calculate and use these.
Reply


Messages In This Thread
RE: Why recursive function consumes more of processing time than loops? - by csr - May-20-2021, 12:31 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Don't Understand Recursive Function muzikman 10 6,593 Mar-08-2025, 01:58 PM
Last Post: bterwijn
  Execution of Another Recursive Function muzikman 6 5,072 Mar-08-2025, 01:57 PM
Last Post: bterwijn
  Continue Function for Loops in Python Hudjefa 5 1,414 Aug-13-2024, 10:27 AM
Last Post: Hudjefa
  return next item each time a function is executed User3000 19 6,116 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  with open context inside of a recursive function billykid999 1 1,430 May-23-2023, 02:37 AM
Last Post: deanhystad
  time function does not work tester_V 4 4,915 Oct-17-2021, 05:48 PM
Last Post: tester_V
  Real Time Audio Processing with Python Sound-Device not working Slartybartfast 2 6,880 Mar-14-2021, 07:20 PM
Last Post: Slartybartfast
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 10,991 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Can you end the Time.sleep function boier96 9 17,989 Jan-16-2021, 10:09 PM
Last Post: Serafim
  Real Time signal processing tagalog 2 3,722 Dec-12-2020, 05:23 AM
Last Post: tagalog

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020