[英]Java tail recursion : Is below Fibonacci code tail recursive ?
I recently learnt about tail recursion. 我最近了解了尾递归。 I understand, many programming language compilers perform[Current java doesn't] s, code optimization when it finds a recursive method a "Tail recursive".
我了解,许多编程语言编译器在找到递归方法“尾递归”时会执行代码优化。
My understanding of TR : Compiler, does not create new stack frame(instead replace with older call's stack frame) when there is no further operation to be performed after the call has returned. 我对TR的理解:编译器在调用返回后不再执行任何操作时不会创建新的堆栈框架(而是替换为较早的调用的堆栈框架)。
Is below code[ even though in java] a tail recursive ? 下面的代码[即使在Java中]是尾递归的吗?
suppose totalSeriesLenght = 10. 假设totalSeriesLenght = 10。
public void generateFibonacciSeries(int totalSeriesLenght) {
int firstNum = 0;
int secondNum = 1;
printNextFibonacciNumber(firstNum, secondNum,totalSeriesLenght);
}
public void printNextFibonacciNumber(int fiboOne , int fiboTwo,int totalSeriesLenght) {
if(totalSeriesLenght >= 1) {
System.out.print(fiboOne + ",");
int fiboNext = fiboOne + fiboTwo;
totalSeriesLenght --;
printNextFibonacciNumber(fiboTwo, fiboNext,totalSeriesLenght);
}
}
Yes the function call is tail-recursive, but Java does not have any tail call optimization, so new stack frames will be created. 是的,函数调用是尾部递归的,但是Java没有任何尾部调用优化,因此将创建新的堆栈框架。
As proof consider the following program: 作为证明,请考虑以下程序:
public class Test{
public static void main(String[] args){
recursive();
}
public static void recursive(){
recursive();
}
}
running this program results in a StackOverflowError which means that the stack had to be filled with something: stack frames! 运行该程序会导致StackOverflowError,这意味着堆栈中必须填充某些东西:堆栈框架!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.