3 ms·
Sorry for the late reply. > If you use recursion, both the absolutely necessary state and the temporaries are pushed onto the stack (along with the stack frame
by dataflow 2mo ago
Sorry for the late reply.
> If you use recursion, both the absolutely necessary state and the temporaries are pushed onto the stack (along with the stack frame the language runtime wants). If you use iteration, the programmer just pushes the necessary state onto the stack, and reuses the temporaries in place.
If that's the statement, what you (addressing both yourself & the OP) are arguing here is that it's easier to avoid unintentional temporaries with iteration. Nobody argued against that, it's obviously true. It clearly doesn't mean iteration is always faster, it just means achieving one particular outcome is easier with it.
Before you drop your mic though: what you're missing here the ugly half of the picture, which is that this is because managing any state in the iterative version of arbitrary recursive calls is already a massive pain across calls [1], so of course you're unlikely to maintain unneeded state.
Basically, when it comes to iteration, you're assuming arbitrary amounts of effort (I guess because it wouldn't run at all otherwise, let alone quickly), but when it comes to recursion, suddenly you're assuming low effort (I guess because low optimization effort still gets it running, just less quickly).
That's... clearly an unfair comparison, and generalizing it to "iteration is faster than recursion" is silly.
P.S.: I should perhaps point out that compilers can & do partially inline even unbounded recursion. For you to argue iteration is faster, you'd have to basically argue that compilers can (and do) make analogous optimizations for the equivalent iterative versions of the same algorithms (read: manual management of a stack buffer, etc.) across equivalent level traversals of the algorithm. Do you actually believe that to be true? I'm not gonna proclaim this is impossible or that compilers never do this, but I can say I sure as heck don't recall ever seeing or hearing of this. From what I've seen, iteration would generate shorter code, not necessarily faster code.