3 ms·
> Recursion takes up precious memory on the call stack! There may be commands to increase the call stack size for your program, but there is only so much the OS
by pcl 3y ago
> Recursion takes up precious memory on the call stack! There may be commands to increase the call stack size for your program, but there is only so much the OS will allow. Memory on the heap is much less restricted.
This reasoning implies that tail call optimization is some sort of memory-segmentation workaround. This isn't accurate.
A (non-TCO) recursive approach is more expensive because it uses O(n) bookkeeping memory, whereas the iterative approach uses O(1) memory. Naive recursion will allocate a stack frame for each "iteration", whereas the loop approach will not allocate anything per iteration.
So, the iterative approach simply uses much less memory for large iteration counts; the placement of the memory in stack space or heap space isn't the relevant factor.
- fyrn_ 3y agoBut without TCO, even if your function doesn't have any state of it's own, it will use memory on the call stack. I don't think anything about what they said implied memory segmentation was the problem. It's pretty clear they mean each recusion increases the size of the call stack without TCO.
- rezonant 3y agoAgreed, I think the mention of heap space was more to answer the question of someone new to this topic of "but wait, I can allocate gigabytes of data in an array, why can't I allocate 100,000 stack frames?"