Home > Java > javaTutorial > body text

How to test recursion and loops in Java?

PHPz
Release: 2023-04-23 19:40:16
forward
1490 people have browsed it

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);      }  }  }
Copy after login

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;          }      }  }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template