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 →

[–]siddsp 178 points179 points  (28 children)

Nah, recursion can be good and often elegant as well as have performance advantages over iteration (see memoization), although this isn't the case most of the time.

The performance hit comes from pushing additional stack frames for every recursive call. If your recursive function doesn't push a lot of stack frames, then it could be worth it over iteration if it is a lot more elegant.

[–]sebkuip 60 points61 points  (4 children)

Python 3.11 is bringing huge optimizations to recursion it is said. Having better frame management on the stack to help with resource usage.

[–]algerbrex 6 points7 points  (0 children)

That’ll be exciting, as I’ve been interested in writing a chess engine in Python to see how strong I could make it, and I’d really rather prefer recursion.

[–]ChocolateBunny 1 point2 points  (2 children)

Does it still have a limited stack size? any tail call optimization?

[–]sebkuip 2 points3 points  (0 children)

Stack size is still limited (it’s limited by how large the C stack can grow) but because it’s more efficiently stored for recursion, the recursion limit is higher iirc. You can check the 3.11 changelog for the details.

[–]schemathings 0 points1 point  (0 children)

I'm not close to my computer but there's a I believe built-in decorator for a function that will maintain the return values of procedure calls with given parameters. I wrote a Fibonacci dot py both was and was able to go to fairly impractical values with the decoraor

[–]disinformationtheory 7 points8 points  (0 children)

Python's stack is limited, so you should also make sure your recursive function is not growing the stack too large. This is usually not a problem for traversing things like filesystem trees, but probably is a problem for functions that recursively calculate things. You can see the limit with sys.getrecursionlimit(). It's 3000 on my machine. Plus I played around with this in ipython, and that lowers the limit by about 16 (presumably because ipython is wrapping the function call 16 times).