Recursive and loop
1. Slow Recursion
Recursion means that the function calls itself. Each time a function is called, the following content must be stored in the recursive Stack: the address of the called function, the form parameter, the local variable, and the return value. Therefore, if N recursive calls are performed, the stack operation will save N * Call function addresses, N * local variables, N * parameters, and N * return values. This will inevitably affect efficiency.
2. Comparison of recursion and loop:
Recursion and loop are two different ways to solve the problem. We cannot say that the efficiency of a loop is always higher than that of recursion. Let's make a simple analysis below:
1. recursion:
Advantage: the code is concise and clear
Disadvantage: its operation requires a large number of function calls. If the number of call layers is deep, additional stack processing is required, and even Stack Overflow may occur. Recursive operations involve operations such as stack pressure and stack bounce, which may affect the execution efficiency.
If the compiler optimizes the efficiency of function calls, the recursive efficiency may not be lower than the loop.
2. Loop:
Advantages: simple structure and fast (relative)
Disadvantage: it cannot solve all problems. Some problems are applicable to recursion rather than loop (for example, factorial ).
Of course, if you use a loop to solve the problem easily, you 'd better use a loop.
3. What stack does recursion use?
Stack is divided into two types: System stack and user stack, which are used recursively.
1. The system stack (also known as the core stack and kernel stack) is a part of the operating system space in the memory. Its main purposes are as follows:
(1). Save the interrupted scene. For nested interruptions, the field information of the interrupted program is pushed into the system stack at one time, and the reverse order pops up when the interrupted response is returned.
(2). Save the return points, parameters, local variables, and return values of mutual calls between sub-processes of the operating system.
2. the user stack is an area in the user process space. The user saves the return points, parameters, local variables, and return values that are called by subprograms of the user process.