7 ms·
How can tail recursion have better performance if they both compile to the same machine instruction - a conditional jump?
by guntars 2y ago
How can tail recursion have better performance if they both compile to the same machine instruction - a conditional jump?
- suprjami 2y agoBecause it results in a tail call and you don't have to build a new stack frame.
- guntars 2y agoA loop didn’t have to build a stack frame in the first place. Once the optimizer has done it’s job, both the TCO optimized tail call and a basic loop will have the same instructions, hence the performance will be the same.
- suprjami 2y agoYes, that's exactly the point I am making. Modern compilers optimise this for you, exactly as you said. Back in the 80s compilers didn't do this. There really was a difference between the machine code emitted for a naive loop and a tail call loop. A lot of advice to rewrite naive loops to do tail calls is based on that 1980s compiler behaviour, not on the optimising 2020s compiler behaviour.