神刀安全网

Difference between Stack and Heap memory in C#

In this article, we will discuss:

  • What is Stack Memory?
  • What is Heap Memory?
  • Difference between Stack and Heap memory
  • Example
  • Summary

What is Stack?

The stack is an array of memory.

  • It is a Last-in, First-out (LIFO) data structure.
  • Data can be added to and deleted only from the top of the stack.
  • Placing a data item at the top of the stack is called pushing the item onto the stack.
  • Deleting an item from the top of the stack is called popping the item from the stack.

Stack stores various types of data:

  • The values of certain types of variables
  • The program’s current execution environment
  • Parameters passed to methods

What is Heap Memory?

The heap is an area of memory where chunks are allocated to store certain kinds of data objects. Unlike the stack, data can be stored and removed from the heap in any order. your program can store items in the heap, it cannot explicitly delete them. Instead, the CLR’s garbage collector (GC) automatically cleans up orphaned heap objects when it determines that your code can no longer access them.

Difference between Stack and Heap memory

Difference between Stack and Heap memory in C#

Example:

Let’s look at below example to understand it better.Let’s look at a method that adds two integers.

int add(int a, int b) {   return a+b; } 

When you call this method like this:

int a = 20;//stored on the main stack, needs to be copied into the function body int b = 32;//stored on the main stack, needs to be copied into the function body int result = add(x,y);//result is copied from function to main stack 

integers 20 and 32 are copied into the add() stack and the result is allocated on the add’s stack and then copied back to the result.

There is another way of implementing this example.

int add() {   return this.a+this.b; } this.a=20;//stored on a heap this.b=32;//stored on a heap int result=add();//result is copied from function to main stack 

Even though this method has no arguments, fields a and b are copied from heap to the program stack before being operated in add().

Summary:

In this article, we have discussed:

  • What is Stack?
  • What is Heap?
  • Difference between Stack and Heap memory
  • Example

Thanks for visiting !!

© 2016,admin. All rights reserved.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Difference between Stack and Heap memory in C#

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址