This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

What is recursion

The method itself is called recursively.

However, the disadvantage of recursion algorithms is that they consume a lot of stack memory, so try not to use them when you can. In addition, recursion must have an end condition, otherwise stack memory overflow errors will occur; Even with the end condition, a stack overflow error can occur because the recursion is too deep.

The principle of

The following is the Java language as an example to illustrate the principles of recursion knowledge

1. Memory space of the JVM

There are three main blocks of memory partition in the JVM:

  • Method area memory: The memory space into which the class bytecode snippet is loaded during class loading;
  • Heap memory: New objects are stored in heap memory;
  • Stack memory: When a method snippet executes, it allocates memory space to the method and pushes the stack in the stack memory. It stores local variables.

Method (function) code snippets are stored in the method area when the class is loadedThe code snippet is only one copy in the method area memory, but it can be called repeatedly. Each time this method is called, memory space needs to be allocated for this method in stack memory.

Method at the moment of calling, will allocate memory space for this method, will occur in the stack pressure action; After the execution of the method, all the allocated memory space for the method is released, and the stack bounce action occurs.

2. Example: Find the factorial of 3

package practice;

public class pr1 {
	
	
	public static void main(String[] args) {
		int n=3;
		int result = sum(n);
		System.out.println(result);
		
	}
	
	public static int sum(int n) {
		if(n==1) {
			return 1;
		}
		return n*sum(n-1); }}Copy the code

Code execution, first run the main function (program entry), the main function into the stack memory, and store variables; Main calls sum, sum pushes the stack, and sum keeps calling itself until n==1. After the method is executed, the stack is removed one by one.