Showing posts with label stack. Show all posts
Showing posts with label stack. Show all posts

Saturday, June 11, 2011

.NET interview questions :- What are stack , heap , value , reference types , boxing and unboxing ?

Stack and heap are memory types in an application. Stack memory stores data types like int , double , Boolean etc. While heap stores data types like string and objects.

For instance when the below code runs the first two variables i.e. “i” and “y” are stored in a stack and the last variable “o” is stored in heap.

void MyFunction()
{
int i = 1; // This is stored in stack.
int y = i; // This is stored in stack.
object o = null; // This is stored in heap.
} // after this end the stack variable memory space is reclaimed while //
the heap memory is reclaimed later by garbage collector.

Value types contain actual data while reference types contain pointers and the pointers point to the actual data.

Value types are stored on stack while reference types are stored on heap. Value types are are your normal data types like int , bool , double and reference types are all objects.

When value type is moved to a reference type it’s called as boxing. The vice-versa is termed as unboxing.

Attaching to the above one more c# interview which comes up is What is boxing and unboxing , below is the video which explains the same.



Please click here to see more Most asked c# interview questions

Monday, November 29, 2010

.NET and C# interview questionsBoxing, Unboxing, Heap, Stack, By reference and by value

.NET and C# interview questions Boxing, Unboxing, Heap, Stack, By reference and by value


Also see
Important .NET interview questions and answers part 1
Important .NET interview questions and answers part 2

Recently I went for a big IT multinational company and the interviewer grilled me in for a hour around the below concepts Boxing , Unboxing , Heap , Stack , By reference and by value. I am just putting my experience so that every one can be benefitted. The above 6 concepts are very much interlinked and asked by C# interviewers again and again. They can start from anyone of the three sections i.e. boxing / unboxing , Stack / Heap or By ref and value.

From which ever section they initiate the discussion, all interviewers touch base the above concept directly indirectly. In my particular C# interview he started first with...

What are stack's and heaps ?

Stack are like series of compartment i.e. one above another. It keeps track of your running memory needed by your application. On the other hand heap is nothing but pile of objects which are kept one above another and they can be reached any moment of time.

I knew that I had answered right but he was not expecting that answer he was expecting something else....So bang came the next question.

So what kind of data stack has and heap has ?

Both stack and heap are memory types. Stack memory are value types like integer , double , Boolean etc , while heap memory are objects and string data types.

Once I answered the above question , I was expecting the next question on what are value types and references. But he went some other route but again near to expectation ...

How is boxing and unboxing related to the above concept ?

Boxing happens when data moves from value type to reference type and unboxing happens when data moves from reference types to value types.

This leads to a small performance hit in the application.

I purposely put the last line so that he would probe further on performance and yes yes , he asked me the next question...Its my simple old trick to force the interviewer to ask question which i am good at..;-)

Why does performance decrease when boxing and unboxing happens ?

In boxing and unboxing data moves from value to reference and vice versa which needs quite a bit processing as they are different memory types all together. Due to the same there is a performance decrease when the boxing and unboxing phenomenon happens.

I knew this was becoming a in-depth discussion forum and the next question but obvious was ...

So how can we avoid boxing and unboxing ?

We can not really avoid , but where ever possible we can do two things at least :-



  • First is avoid unnecessary conversions.


  • Second use generics to avoid the conversion situation.

What are the scenarios in which boxing and unboxing happens ?

One of the common situation is when we take data in to UI object like text boxes and we need to move the data in to a value data type like integer , double etc. As the UI textboxes and controls are objects its very difficult to avoid this scenario.

Are string by val or by ref ?

They are by ref. String and objects are by ref and they are always stored in a heap. All the other data types other than these 2 are value types.

This question was unexpected...but i had my concepts clear..so.

How do stack and heap memory gets claimed back when the application exits ?.

Stack is the running memory , the byval memory , So it just gets claimed when the application exits. The by ref memory or heap memory is not claimed as soon as the application exits , but its claimed by the garbage collector routine. So the GC just spawns and claims the memory acquired by the heap.

By Shivprasad Koirala.

Tuesday, April 27, 2010

6 important .NET concepts: - Stack, heap, Value types, reference types, boxing and Unboxing.

Introduction


This article will explain 6 important concepts Stack , heap , value types , reference types , boxing and unboxing. This article starts first explaining what happens internally when you declare a variable and then it moves ahead to explain 2 important concepts stack and heap. Article then talks about reference types and value types and clarifies some of the important fundamentals around them.

Finally the article concludes by demonstrating how performance is hampered due to boxing and unboxing with a sample code.

Watch my 500 videos on various topics like design patterns,WCF, WWF , WPF, LINQ ,Silverlight,UML, Sharepoint ,Azure,VSTS and lot more
click here
, you can also catch me on my trainings @ click here.



Image taken from http://michaelbungartz.wordpress.com/

What goes inside when you declare a variable?

When you declare a variable in a .Net application, it allocates some chunk of memory in to the RAM. This memory has 3 things first the name of the variable, second data type of the variable and finally the value of the variable.

That was a simple explanation of what happens in the memory, but depending on what kind of data type your variable is allocated on that type of memory. There are two types of memory allocation stack memory and heap memory. In the coming sections we will try to understand these two types of memory in more details.

Stack and Heap

In order to understand stack and heap, let’s understand what actually happens in the below code internally.
public void Method1()
{
// Line 1
int i=4;

// Line 2
int y=2;

//Line 3
class1 cls1 = new class1();
}


It’s a 3 line code so let’s understand line by line how things execute internally.
Line 1:- When this line is executed compiler allocates a small amount of memory in to memory type called as stack. Stack is responsible of keeping track of running memory needed in your application.

Line 2:- Now the execution moves to the next step. As the name says stack it stacks this memory allocation on the top of the first memory allocation. You can think about stack as series of compartment or boxes put on top of each other.
Memory allocation and de-allocation is done using LIFO (Last in first out) logic. In other words memory is allocated and de-allocated at only one end of the memory i.e. top of the stack.

Line 3:- In line 3 we have a created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called as ‘Heap’. ‘Heap’ does not track
running memory it’s just pile of objects which can reached at any moment of time. Heap is used for dynamic memory allocation.

One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword it allocates on "HEAP".
Exiting the method (The fun):- Now finally the execution control starts exiting the method. When it passes the end control it clears all the memory variables which are assigned on stack. In other words all variables which are related to ‘int’ data type are de-allocated in ‘LIFO’ fashion from the stack.
The BIG catch – It did not de-allocate the heap memory. This memory will be later de-allocated by “GARBAGE COLLECTOR”.


Now many of our developer friends must be wondering why two types of memory, can’t we just allocate everything on just one memory type and we are done.
If you look closely primitive data types are not complex, they hold single
values like ‘int i = 0’. Object data types are complex, they reference other
objects or other primitive data types. In other words they hold reference to other multiple values and each one of them must be stored in memory. Object types need dynamic memory while primitive needs static type memory. If the requirement is of dynamic memory it’s allocated on a heap or else it goes on a stack.
Image taken from http://michaelbungartz.wordpress.com/


Value types and reference types

Now that we have understood the concept of ‘Stack’ and ‘Heap’ it’s time to understand the concept of value types and reference types.
Value types are types which hold both data and the memory on the same location. While a reference type has a pointer which points to the memory location.
Below is a simple integer data type with name ‘i’ whose value is assigned to an other integer data type with name ‘j’. Both these memory values are allocated on the stack.
When we assign the ‘int’ value to the other ‘int’ value it creates a complete different copy. In other word if you change either of them the other does not change. These kinds of data types are called as ‘Value types’.



When we create an object and when we assign one object to the other object, they both point to the same memory location as show in the below code snippet. So when we assign ‘obj’ to ‘obj1’ they both point to the same memory location.
In other words if we change one of them the other object is also affected this is termed as ‘Reference types’.


So which data types are ref type and value type?

In .NET depending on data types the variable is either assigned on the stack or on the heap. ‘String’ and ‘Objects’ are reference types and any other .NET primitive data types are assigned on the stack. Below figure explains the same in a more detail manner.


Boxing and Unboxing

WOW, you have given so much knowledge, so what’s the use of it in actual
programming. One of the biggest implications is to understand the performance hit which is incurred due to data moving from stack to heap and vice versa.
Consider the below code snippet. When we move a value type to reference type the data is moved from the stack to the heap. When we move reference type to a value type the data is moved from the heap to the stack.
This movement of data from the heap to stack and vice-versa creates a
performance hit.

When the data moves from value types to reference types its termed as ‘Boxing’ and the vice versa is termed as ‘UnBoxing’.



If you compile the above code and see the same in ILDASM you can see in the IL code how ‘boxing’ and ‘unboxing’ looks, below figure demonstrates the same.


Performance implication of Boxing and unboxing

In order to see how the performance is impacted we ran the below two
functions 10,000 times. One function has boxing and the other function is simple. We used a stop watch object to monitor the time taken.
The boxing function was executed in 3542 MS while without boxing the code was executed in 2477 MS. In other words try to avoid boxing and unboxing. In project you always need boxing and unboxing , use it when it’s absolutely necessary.
With the same article the sample code is attached which demonstrates this performance implication.



Currently I have not put a source code for unboxing but the same hold true for the same. You can write the same and experiment it by using stopwatch class.