Stack Frames
When a method is called, memory is allocated at the top of the stack to hold a number of data items associated with the method.
This chunk of memory is called the stack frame for the method.
This code produces the following output:
Here's memory inside look like:
-
The stack frame contains memory to hold the following:
- The return address—that is, where to resume execution when the method exits
- Those parameters that allocate memory—that is, the value parameters of the method, and the parameter array if there is one
- Various other administrative data items relevant to the method call
- When a method is called, its entire stack frame is pushed onto the stack.
- When the method exits, its entire stack frame is popped from the stack. Popping a stack frame is sometimes called unwinding the stack.
class Program { static void MethodA( int par1, int par2) { Console.WriteLine("Enter MethodA: {0}, {1}", par1, par2); MethodB(11, 18); // Call MethodB. Console.WriteLine("Exit MethodA"); } static void MethodB(int par1, int par2) { Console.WriteLine("Enter MethodB: {0}, {1}", par1, par2); Console.WriteLine("Exit MethodB"); } static void Main( ) { Console.WriteLine("Enter Main"); MethodA( 15, 30); // Call MethodA. Console.WriteLine("Exit Main"); } }
This code produces the following output:
Enter Main
Enter MethodA: 15, 30
Enter MethodB: 11, 18
Exit MethodB
Exit MethodA
Exit Main
Enter MethodA: 15, 30
Enter MethodB: 11, 18
Exit MethodB
Exit MethodA
Exit Main
Here's memory inside look like:
Recursion
Besides calling other methods, a method can also call itself. This is what we call recursion.
Recursion can produce some very elegant code, such as the following method for computing the factorial of a number.
Lets see on our
This code will result:
The mechanicm of a method calling itself are exactly the same as if it had called another, different method. A new stack frame is pushed onto the stack for each call to the method.
Recursion can produce some very elegant code, such as the following method for computing the factorial of a number.
Lets see on our
Factorial
method—factorial 3 means 1 * 2 * 3.
static int Factorial(int inVal) { if (inVal <= 1) { Console.Write(inVal + " "); return inVal; } else { int fact = inVal * Factorial(inVal - 1); // Call Factorial again. Console.Write(fact + " "); return fact; } } static void Main(string[] args) { Factorial(4); }
This code will result:
1 2 6 24
The mechanicm of a method calling itself are exactly the same as if it had called another, different method. A new stack frame is pushed onto the stack for each call to the method.
Eventough recursion can provide you ellegant code, but be careful to use it.
Using recursion can lead to unmanage stack frames usage.
Using recursion can lead to unmanage stack frames usage.
0 comments:
Post a Comment