5

Below is some code written iteratively with mild resemblance to the DBSCAN algorithm:

rw = 100
for r in range(rw):
    neighs = retrieve_neighs(r)
    # rest of body

If I rewrite it using recursion, I might write:

rw = 100
def foo(r):
    if r < rw:
        neighs = retrieve_neighs(r)
        # rest of body
        foo(r + 1)
foo(0)

I expect retrieve_neighs to return a list (or some collection) of points - this opens up the possibility that an entire file of data could be loaded, right? Is there any recognition that neighs is not used after

foo(r + 1)

and so the memory neighs refers to is freed?

1
  • You can delete your neighs object once you are done with performing some operation on it. And if your are returning a list then you can create a generator object instead of whole list. Commented Dec 27, 2014 at 4:59

1 Answer 1

5

What you're describing is a major effect of tail call optimization, which Python explicitly doesn't do because Guido feels that it isn't worth the tradeoffs, especially in terms of debugging information. If the recursive version of the algorithm is clearer, you might consider explicitly doing del neighs once you no longer need it - this has the save effect as the variable falling out of scope, potentially making it eligible for garbage collection.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.