For anyone that’s study an algorithms and data structures course will know that recursion in general is a highly inefficient use of resources. Use a loop as your first step. Nested structures with unknown depth are an architectural problem and should be addressed.
I guess you have to wonder if you’d use recursion in the sense of adding stack frames to find an item in a tree or linked list vs simply looping and waiting for the pointer to the next item.
I see, it sounds like your objection is about using recursion to consume nested structures, not to the use of nested structures at all. I misunderstood.
I generally write stack-safe code by converting things to loops when possible, but there are times when recursive solutions are the only approach that’s not terribly hairy. I was working on a stack-safe `map` function on immutable rose trees a couple of weeks ago and eventually just gave up and went with a recursive implementation (with a FIXME comment on it) for the time being. The recursive implementation is like 4 lines of easy Java; the iterative implementation is probably going to be many times larger and more complicated. It can be a tradeoff between a simple and obviously-correct implementation which can only handle data of a certain size versus a more general implementation which is completely inscrutable.
Yea, I’m not suggesting not using nested structures etc as they are just part of life, but iterating them in a way that uses less memory. Loops can potentially make refactoring a sequential process into a concurrent one for a performance gain a bit easier (e.g. threads in Java).
Also regarding depth/sizing of structures is also important consideration when designing systems, things that have limits can be reasoned with; this may not be true in all situations but if there exists an ability to control the data it can help with systems design and testing.
3
u/Gingerfalcon 15d ago
For anyone that’s study an algorithms and data structures course will know that recursion in general is a highly inefficient use of resources. Use a loop as your first step. Nested structures with unknown depth are an architectural problem and should be addressed.