Home  >  Article  >  Java  >  How to test recursion and loops in Java?

How to test recursion and loops in Java?

PHPz
PHPzforward
2023-04-23 19:40:161488browse

Test the execution efficiency and system overhead of recursion and looping (for is used here). First, post an example problem: Implementing the Fibonacci sequence F(n)=F(n-1) F(n-2)

Test environment Eclipse

1. First we use recursion to implement

package com.youfeng.test;   public class Fab {//递归   public static void main(String [] args){       System.out.println(F(40));   }   public static Long F(int index){       if(index==1||index==2){           return 1L;      }      else{          return F(index-1)+F(index-2);      }  }  }

2. Use for loop to implement

package com.youfeng.test;  public class Fab2 {//循环      public static void main(String [] args){          System.out.println(F(40));      }      public static Long F(int index){          if(index==1||index==2){              return 1L;          }          else{              Long f1=1L;              Long f2=1L;              Long f=0L;              for(int i=0;i<index;i++){                  f1=f2;                  f2=f;                  f=f1+f2;              }              return f;          }      }  }

When the value of index is very small, we execute it separately There is no difference. We can't feel any difference in execution speed, but when you adjust the index to a large enough value, 100, 200, 300, 1000... the for loop can easily handle the execution speed very quickly.

When using recursion, you will find obvious jams. Are there any? Call the system resource manager to see your system overhead (you may not be able to open the resource manager because you are stuck).

The above is the detailed content of How to test recursion and loops in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete