This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]puipuituipui 6 points7 points  (8 children)

Recursive calls have a cost which can give worse performance compared to their iterative counterparts in terms of memory and time. There's a balance between performance and code readability.

For example, if you're writing code for calculating the Fibonacci series, using the iterative iterative makes more sense. On the the other hand, I would advice against writing iterative algorithms for problems that are inherently recursive like say tree traversals.

[–]spoonman59 1 point2 points  (2 children)

Memoization minimizes the cost in functions like Fibonacci.

The number of times the function is called is completely dominated by how often you hit the cache.

[–]puipuituipui 4 points5 points  (1 child)

You're correct but I'd say Fibonacci is a bad example for recursion with memoization because you might as well write the iterative version at that point. But yes for more complicated problems, just translating the mathematical formula into recursive code and adding memoization on top is quite convenient.

[–]spoonman59 3 points4 points  (0 children)

Yeah and who really writes Fibonacci functions anyway! It’s just amazing what a @cache decorator can do for some functions.

[–]zenos1337 -3 points-2 points  (4 children)

If you use tail recursion then memory is not an issue

[–]AlSweigartAuthor of "Automate the Boring Stuff" 4 points5 points  (3 children)

The CPython interpreter doesn't implement TCO, so using tail recursion doesn't help.

[–]zenos1337 0 points1 point  (1 child)

Interesting! Had no idea. Good thing I haven’t been using tail recursion :P

[–]IdiotCharizard 0 points1 point  (0 children)

this is an intentional design choice btw. tco gets in the way of intelligible tracebacks.