4 ms·
Recursion as a concept is useful. In practice, you can sometimes achieve better performance (or avoid exceeding some call stack limit) by doing it "iteratively"
by hot_gril 4y ago
Recursion as a concept is useful. In practice, you can sometimes achieve better performance (or avoid exceeding some call stack limit) by doing it "iteratively" in a way that's still conceptually equivalent to recursion, i.e. with a stack you manually manage. I've never had a function call itself in C++, but I've done conceptually recursive things a lot in it.
- fooker 4y agoManually managing a stack is significantly more expensive compared to utilizing the call stack for recursion. Modern hardware and calling conventions are designed to make call stacks fast. You should measure this!
- hot_gril 4y agoFor my job involving C++, it doesn't matter which is faster. Just doing whatever is more readable, and since I'm usually doing a DFS/BFS func, it's nice being able to easily toggle that by popping from front vs back. When I'm not, I'd rather have a readable stack trace if something goes wrong and not have to deal with the oddities of recursive lambdas. In Python, the issue is the easily reachable max recursion depth. Tail recursion isn't optimized. In Erlang, you use recursion even just to iterate through a list. It's fine, the language is made for that.
- fooker 4y agoMy comment was in response to your 'better performance' point. I agree with your other points of course.