English 中文(简体)
什么是尾递归优化?[重复]
原标题:What is tail recursion optimization? [duplicate]
问题回答

A打电话给B,B打电话给C,C打电话给D。

最后你有尾巴:

d returns to c returns to b returns to a. if all these do nothing (like in recursion, where it is actually a calls a calls a calls a) then you can optimize that... ...into d returns to a.

尾递归并不意味着将递归调用转换为循环。

这意味着在递归调用点时,堆栈帧不再必要,因此可以消除。如果递归调用是方法中的最后一个语句,并且递归调用的返回值是当前方法的返回值,则会发生这种情况。通过消除当前堆栈帧,递归调用可以深入到任意深度,而不会出现堆栈溢出错误,并且可以节省大量资源。

这个优化通常是由编译器/解释器来完成,而不是由程序员来完成。

在《JavaScript高级程序设计》中,Crockford说:“有些语言提供了尾递归优化。这意味着如果函数返回递归调用自身的结果,则调用将被替换为循环,这可以显著提高速度。”





相关问题
Recursive same-table query in SQL Server 2008

I have the following table in a SQL Server 2008 database: Id Name ParentFolder -- ---- ------------ 1 Europe NULL 2 Asia NULL 3 Germany 1 4 UK 1 5 China ...

Finding a class within list

I have a class (Node) which has a property of SubNodes which is a List of the Node class I have a list of Nodes (of which each Node may or may not have a list of SubNodes within itself) I need to be ...

Selecting records during recursive stored procedure

I ve got a content management system that contains a hierarchical structure of categories, with sub-categories subject to different ordering options at each level. Currently, that s retrieved by a (...

热门标签