banner



How Register Value Be Placed In The Stack

Introduction

Even though with the .NET framework nosotros don't have to actively worry about retentiveness direction and garbage collection (GC), we notwithstanding accept to keep retentiveness management and GC in heed in society to optimize the performance of our applications. Besides, having a basic understanding of how memory management works will help explain the behavior of the variables nosotros work with in every program we write.  In this article, I'll comprehend the basics of the Stack and Heap, types of variables, and why some variables work equally they do.

There are two places the .Net framework stores items in memory as your code executes.  If you haven't already met, allow me introduce you to the Stack and the Heap.  Both the stack and heap assist us run our code.  They reside in the operating retention on our motorcar and contain the pieces of information we demand to make it all happen.

Stack vs. Heap: What's the difference?

The Stack is more or less responsible for keeping rails of what's executing in our code (or what's been "called").  The Heap is more than or less responsible for keeping rail of our objects (our information, well... most of it - we'll get to that later.).

Think of the Stack as a series of boxes stacked one on tiptop of the next.  We keep track of what's going on in our application by stacking another box on height every time we call a method (called a Frame).  We tin can but use what's in the acme box on the stack.  When we're done with the peak box (the method is done executing) we throw it away and proceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that its purpose is to concur information (non go along track of execution most of the time) so anything in our Heap can exist accessed at any time.

With the Heap, there are no constraints every bit to what can be accessed like in the stack.  The Heap is like the heap of clean laundry on our bed that nosotros have not taken the fourth dimension to put abroad yet - nosotros can take hold of what we need quickly.  The Stack is like the stack of shoe boxes in the cupboard where we have to accept off the pinnacle 1 to get to the one underneath it.

C# Heap(ing) Vs Stack(ing) In .NET


The motion-picture show in a higher place, while not really a true representation of what'southward happening in retentiveness, helps u.s.a. distinguish a Stack from a Heap.

The Stack is cocky-maintaining, meaning that it basically takes intendance of its own retentiveness management.  When the top box is no longer used, information technology'due south thrown out.  The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with how to go along the Heap clean (no 1 wants dirty laundry laying around... it stinks!).

What goes on the Stack and Heap?

We have 4 main types of things nosotros'll exist putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions.

Value Types

In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType):

  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • brusque
  • struct
  • uint
  • ulong
  • ushort

Reference Types

All the "things" declared with the types in this listing are Reference types (and inherit from System.Object... except, of form, for object which is the System.Object object):

  • class
  • interface
  • delegate
  • object
  • cord

Pointers

The third type of "matter" to be put in our memory management scheme is a Reference to a Type. A Reference is often referred to as a Pointer.  Nosotros don't explicitly utilise Pointers, they are managed by the Common Language Runtime (CLR). A Arrow (or Reference) is different than a Reference Type in that when we say something is a Reference Type is a means we access it through a Pointer.  A Pointer is a chunk of space in memory that points to another space in retentiveness.  A Pointer takes up space merely like any other thing that we're putting in the Stack and Heap and its value is either a memory accost or nada.

C# Heap(ing) Vs Stack(ing) In .NET

Instructions

You'll see how the  "Instructions" work later in this article...

How is it decided what goes where? (Huh?)

Ok, one last thing and nosotros'll get to the fun stuff.

Here are our ii aureate rules:

  1. A Reference Blazon always goes on the Heap - easy enough, correct?
  2. Value Types and Pointers always become where they were declared.  This is a picayune more circuitous and needs a flake more agreement of how the Stack works to figure out where "things" are declared.

The Stack, as nosotros mentioned earlier, is responsible for keeping track of where each thread is during the execution of our lawmaking (or what'southward been chosen). Y'all can think of it as a thread "country" and each thread has its own stack.  When our lawmaking makes a telephone call to execute a method the thread starts executing the instructions that take been JIT-compiled and live on the method table, it also puts the method's parameters on the thread stack.  Then, as nosotros go through the lawmaking and meet variables within the method they are placed on meridian of the stack.  This will be easiest to understand by example...

Take the following method.

  1. public int  AddFive( int  pValue)
  2. {
  3. int  issue;
  4.       issue = pValue + 5;
  5. return  result;
  6. }

Here's what happens at the very superlative of the stack.  Keep in mind that what we are looking at is placed on top of many other items already living in the stack:

In one case we start executing the method, the method's parameters are placed on the stack (we'll talk more about passing parameters later).

NOTE

The method does not live on the stack and is illustrated simply for reference.

C# Heap(ing) Vs Stack(ing) In .NET

Adjacent, control (the thread executing the method) is passed to the instructions to the AddFive() method which lives in our blazon'due south method table, a JIT compilation is performed if this is the first time nosotros are hitting the method.

C# Heap(ing) Vs Stack(ing) In .NET

As the method executes, we need some retentivity for the "issue" variable and it is allocated on the stack.

C# Heap(ing) Vs Stack(ing) In .NET

The method finishes execution and our consequence are returned.

C# Heap(ing) Vs Stack(ing) In .NET

And all memory allocated on the stack is cleaned up by moving a arrow to the bachelor retentiveness address where AddFive() started and we go down to the previous method on the stack (not seen hither).

C# Heap(ing) Vs Stack(ing) In .NET

In this example, our "result" variable is placed on the stack.  As a thing of fact, every time a Value Type is declared within the body of a method, it will be placed on the stack.

Now, Value Types are besides sometimes placed on the Heap.  Call up the rule, Value Types always get where they were declared?  Well, if a Value Type is declared outside of a method, but within a Reference Type, information technology will be placed within the Reference Type on the Heap.

Here's another example.

If nosotros have the following MyInt course (which is a Reference Type because information technology is a class):

  1. public form  MyInt
  2. {
  3. public int  MyValue;
  4. }

and the following method is executing:

  1. public  MyInt AddFive( int  pValue)
  2. {
  3.       MyInt result =new  MyInt();
  4.       result.MyValue = pValue + 5;
  5. return  outcome;
  6. }

Only as earlier, the thread starts executing the method and its parameters are placed on the thread'south stack.

C# Heap(ing) Vs Stack(ing) In .NET

Now is when it gets interesting...

Considering MyInt is a Reference Blazon, information technology is placed on the Heap and referenced by a Pointer on the Stack.

C# Heap(ing) Vs Stack(ing) In .NET

After AddFive() is finished executing (like in the first example), and we are cleaning up...

C# Heap(ing) Vs Stack(ing) In .NET

we're left with an orphaned MyInt in the heap (in that location is no longer anyone in the Stack continuing around pointing to MyInt)!

C# Heap(ing) Vs Stack(ing) In .NET

This is where the Garbage Drove (GC) comes into play.  Once our program reaches a certain retentivity threshold and we need more Heap space, our GC will kick-off.  The GC will stop all running threads (a FULL Terminate), find all objects in the Heap that are not being accessed by the main program and delete them.  The GC will then reorganize all the objects left in the Heap to make space and accommodate all the Pointers to these objects in both the Stack and the Heap.  As you tin can imagine, this can be quite expensive in terms of performance, so at present y'all can see why it tin be important to pay attention to what's in the Stack and Heap when trying to write high-functioning code.

Ok... That smashing, merely how does it really affect me?

Proficient question.

When we are using Reference Types, we're dealing with Pointers to the type, not the thing itself.  When we're using Value Types, we're using the affair itself.  Clear as mud, right?

Once more, this is best described past example.

If we execute the post-obit method:

  1. public int  ReturnValue()
  2. {
  3. int  x = new int ();
  4.       x = 3;
  5. int  y = new int ();
  6.       y = x;
  7.       y = 4;
  8. return  x;
  9. }

We'll get the value 3.  Simple enough, correct?

All the same, if we are using the MyInt class from before

  1. public grade  MyInt
  2. {
  3. public int  MyValue;
  4. }

and we are executing the following method:

  1. public int  ReturnValue2()
  2. {
  3.       MyInt 10 =new  MyInt();
  4.       10.MyValue = 3;
  5.       MyInt y =new  MyInt();
  6.       y = x;
  7.       y.MyValue = four;
  8. return  x.MyValue;
  9. }

What do we go?...    4!

Why?...  How does x.MyValue get to be 4?... Take a look at what nosotros're doing and see if it makes sense:

In the offset example everything goes equally planned:

  1. public int  ReturnValue()
  2. {
  3. int  10 = three;
  4. int  y = 10;
  5.       y = 4;
  6. render  10;
  7. }

C# Heap(ing) Vs Stack(ing) In .NET

In the next example, nosotros don't get "3" because of both variables "x" and "y" point to the same object in the Heap.

  1. public int  ReturnValue2()
  2. {
  3.       MyInt x;
  4.       x.MyValue = iii;
  5.       MyInt y;
  6.       y = 10;
  7.       y.MyValue = four;
  8. render  10.MyValue;
  9. }

C# Heap(ing) Vs Stack(ing) In .NET

Hopefully, this gives yous a amend understanding of a basic departure between Value Type and Reference Blazon variables in C# and a basic understanding of what a Pointer is and when it is used.  In the next part of this series, nosotros'll get further into memory direction and specifically talk about method parameters.

For now...

Happy coding.

Source: https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i/

Posted by: smithjould1995.blogspot.com

0 Response to "How Register Value Be Placed In The Stack"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel