尾调用
某个函数的最后一步是调用另一个函数。
function f(x){
return g(x) + 1;
}
由于调用后还有操作,即使写在一行内,不属于尾调用。
尾调用由于是函数的最后一步操作,所以不需要保留外层函数的调用记录,因为调用位置、内部变量等信息都不会再用到了,只要直接用内层函数的调用记录,取代外层函数的调用记录就可以了。
比如:
function f() {
let m = 1;
let n = 2;
return g(m + n);
}
f();
但由于调用g之后,函数f就结束了,所以执行到最后一步,完全可以删除 f() 的调用记录,只保留 g(3) 的调用记录。这就叫做"尾调用优化"(Tail call optimization)
尾调用优化(Tail Call Optimization)
TCO is only available in strict mode.
It provides a way to optimise recursive and deeply nested function calls by eliminating the need to push function state onto the global frame stack, and avoiding having to step down through each calling function by returning directly to the initial calling function.
TCO allows for recursive functions to have indefinite recursion as the frame stack will not grow with each recursive call. Without TCO recursive function had a limited recursive depth.
尾调用优化举例说明
function a(){
return b(); // 2
}
function b(){
return 1; // 3
}
a(); // 1
Without TCO the call to a() creates a new frame for that function. When that function calls b() the a()'s frame is pushed onto the frame stack and a new frame is created for function b()
When b() return to a() a()'s frame is popped from the frame stack. It immediately return to the global frame and thus does not use any of the states save on the stack.
TCO recognises that the call from a() to b() is at the tail of function a() and thus there is no need to push a()'s state onto the frame stack. When b(0) returns rather than returning to a() it returns directly to the global frame. Further optimising by eliminating the intermediate steps.
一种特殊的尾调用——尾递归
函数调用自身,称为递归。如果尾调用自身,就称为尾递归。
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
factorial(5) // 120
笔记
- 函数内联是指把被调用的函数体插入调用的函数当中,就好像被调用的函数直接写在调用的函数代码中一样,因此,能节省函数调用和返回的开销(比如,寄存器的保存与恢复)。
- Javascript Garden中谈到arguments与函数内联的问题
function foo() {
arguments.callee; // do something with this function object
arguments.callee.caller; // and the calling function object
}
function bigLoop() {
for(var i = 0; i < 100000; i++) {
foo(); // Would normally be inlined...
}
}
上面代码中,foo 不再是一个单纯的内联函数 inlining(译者注:这里指的是解析器可以做内联处理), 因为它需要知道它自己和它的调用者。 这不仅抵消了内联函数带来的性能提升(内联函数带来的性能提升见第一条),而且破坏了封装,因此现在函数可能要依赖于特定的上下文。
- 解决禁用arguments.callee的办法:
[1,2,3,4,5].map(function factorial(n) {
return (!(n>1))? 1 : factorial(n-1)*n;
});
- arguments.callee.caller对解析器优化有副作用
arguments.callee.caller gives you the function that called you, not the function you're in, which isn't overly useful in real code, and has the effect of making inlining, tail calls, etc unsound.
参考文献
- 跨文件脚本内联:函数内联使得性能提升
- Why was the arguments.callee.caller property deprecated in JavaScript?
- ECMAscript5 的 Strict Mode 中为什么禁止使用 arguments.callee?
- https://stackoverflow.com/documentation/javascript/2355/tail-call-optimization#t=201708230040512939622
- http://www.ruanyifeng.com/blog/2015/04/tail-call.html
- 深入理解递归中的尾调用