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?
#2
I assume your loop is not written identically.

Recursion means a function call. A function call will take more time and memory than just executing a loop. But the difference isn't huge.

But your program is written in a way where you're redoing your work over and over and over. I'm assuming your loop was not written that way. The slowness is due to the algorithm, not inherently the recursion.

If you add a memoization cache to it, it will complete quickly.
from functools import lru_cache

@lru_cache
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(40))
M83Linux likes this post
Reply


Messages In This Thread
RE: Why recursive function consumes more of processing time than loops? - by bowlofred - May-11-2021, 11:50 PM

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