avghdev
avghdev

Reputation: 89

Which is more optimal, infinite recursion or infinite loops?

I'm creating an application in Python that should run in the background making constant checks on the system clipboard. In order to achieve this, I have a method that makes the check and then calls itself after a specified delay (infinite recursion). However, I'm wondering if it would be more optimal to implement an infinite loop rather than recursion.

My first instinct is that a loop might be better because it doesn't retain any pointers to the previous function call - but I'm not really sure.

In short, is this more optimal:

def recursive(interval):
    performChecks()
    updateGUI()
    wait(interval)
    recursive(interval)

or is this

def main():
    running = True
    while running:
        performChecks()
        updateGUI()
        wait(interval)

Upvotes: 1

Views: 109

Answers (1)

wim
wim

Reputation: 362557

In Python, you should prefer the second version. This is because the call stack is by default limited to:

>>> import sys
>>> sys.getrecursionlimit()
1000

So your first approach will crash after 1000 iterations.

Upvotes: 2

Related Questions