而开启尾递归优化后, 就没有新的调用栈生成了, 而是直接pop
bp指向的 _tail_recursion
函数的地址(pushq %rbp)然后返回,
仍旧用的是同一个调用栈!
存在的问题
虽然尾递归优化很好, 但python 不支持尾递归,递归深度超过1000时会报错
RuntimeError: maximum recursion depth exceeded
一个牛人想出的解决办法
实现一个 tail_call_optimized 装饰器
#!/usr/bin/env python2.4# This program shows off a python decorator(# which implements tail call optimization. It# does this by throwing an exception if it is# it's own grandparent, and catching such# exceptions to recall the stack.import sysclass TailRecurseException: def __init__(self, args, kwargs): self.args = args self.kwargs = kwargs