What is tail call optimization?

前端 未结 10 1272
一整个雨季
一整个雨季 2020-11-21 06:36

Very simply, what is tail-call optimization?

More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of wh

10条回答
  •  再見小時候
    2020-11-21 07:26

    TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space. The only situation in which this happens is if the last instruction executed in a function f is a call to a function g (Note: g can be f). The key here is that f no longer needs stack space - it simply calls g and then returns whatever g would return. In this case the optimization can be made that g just runs and returns whatever value it would have to the thing that called f.

    This optimization can make recursive calls take constant stack space, rather than explode.

    Example: this factorial function is not TCOptimizable:

    def fact(n):
        if n == 0:
            return 1
        return n * fact(n-1)
    

    This function does things besides call another function in its return statement.

    This below function is TCOptimizable:

    def fact_h(n, acc):
        if n == 0:
            return acc
        return fact_h(n-1, acc*n)
    
    def fact(n):
        return fact_h(n, 1)
    

    This is because the last thing to happen in any of these functions is to call another function.

提交回复
热议问题