Recently I tried compiling program something like this with GCC:
int f(int i){
if(i<0){ return 0;}
return f(i-1);
f(100000);
and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing the arguments to f. And – the compiler wasn’t even running in optimized mode.
Now, when I try the same thing in Python – I hit maximum recursion wall (or probably stack overflow if i set recursion depth too high).
Is there way that a dynamic language like python can take advantage of these nice optimizations?
Maybe it’s possible to use a compiler instead of an interpreter to make this work?
Just curious!
The optimisation you’re talking about is known as tail call elimination – a recursive call is unfolded into an iterative loop.
There has been some discussion of this, but the current situation is that this will not be added, at least to cpython proper. See Guido’s blog entry for some discussion.
However, there do exist some decorators that manipulate the function to perform this optimisation. They generally only obtain the space saving though, not time (in fact, they’re generally slower)