Introduction

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

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 a lot more: click here.

You can also catch me on my trainings 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 the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.

That was a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated 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 detail.

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=; // Line 2
int y=; //Line 3
class1 cls1 = new class1();
}

It’s a three line code, let’s understand line by line how things execute internally.

    • Line 1: When this line is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the 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 top of the first memory allocation. You can think about stack as a series of compartments 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 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 ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be 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 toint 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 the 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 ones needs static type memory. If the requirement is of dynamic memory, it’s allocated on the 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 memory on the same location. 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 another 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 completely different copy. In other words, 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 an object to another object, they both point to the same memory location as shown 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 types and which are value types?

In .NET depending on the data type, 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. The figure below 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, data is moved from the stack to the heap. When we move a 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, it is termed ‘Boxing’ and the reverse is termed ‘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. The figure below 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 a project where you need boxing and unboxing, use it when it’s absolutely necessary.

With this article, sample code is attached which demonstrates this performance implication.

Currently I have not included source code for unboxing but the same holds true for it. You can write code and experiment it using the stopwatch class.

Source code

Attached with the article is a simple code which demonstrates how boxing creates performance implications. You can download the source code here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

From  Shivprasad koirala

Six important .NET concepts 【Turn】的更多相关文章

  1. 【Android】IntentService & HandlerThread源码解析

    一.前言 在学习Service的时候,我们一定会知道IntentService:官方文档不止一次强调,Service本身是运行在主线程中的(详见:[Android]Service),而主线程中是不适合 ...

  2. (四)play之yabe项目【页面】

    (四)play之yabe项目[页面] 博客分类: 框架@play framework   主页面 显示当前发表博客的完整内容,以及历史博客列表 Bootstrap Job 一个play job任务就是 ...

  3. 【翻译】Sencha Touch2.4 The Layout System 布局

    [翻译]The Layout System 布局 In Sencha Touch there are two basic building blocks: componentsand containe ...

  4. SCI&EI 英文PAPER投稿经验【转】

    英文投稿的一点经验[转载] From: http://chl033.woku.com/article/2893317.html 1. 首先一定要注意杂志的发表范围, 超出范围的千万别投,要不就是浪费时 ...

  5. 企业IT管理员IE11升级指南【8】—— Win7 IE8和Win7 IE11对比

    企业IT管理员IE11升级指南 系列: [1]—— Internet Explorer 11增强保护模式 (EPM) 介绍 [2]—— Internet Explorer 11 对Adobe Flas ...

  6. C程序员必须知道的内存知识【英】

    C程序员必须知道的内存知识[英] 时间 2015-03-08 14:16:11  极客头条原文  http://marek.vavrusa.com/c/memory/2015/02/20/memory ...

  7. 【243】◀▶IEW-Unit08

    Unit 8 Environment I. 不定式(to do)在雅思写作中的运用 1)名词 • 主语(句首) To protect the environment is everyone's dut ...

  8. 【236】◀▶IEW-Unit01

    Unit 1  Fast Food I.动名词的用法 Doing(V-ing) 核心思想:词性是名词,作用是动词 1. 名词 3)主语(句首) 保护环境是我们每个人的责任. Protecting th ...

  9. Uboot中start.S源码的指令级的详尽解析【转】

    本文转载自:http://www.crifan.com/files/doc/docbook/uboot_starts_analysis/release/html/uboot_starts_analys ...

随机推荐

  1. matlab中读取txt数据文件(转)

    根据txt文档不同种类介绍不同的读取数据方法 一.纯数据文件(没有字母和中文,纯数字) 对于这种txt文档,从matalb中读取就简单多了 例如test.txt文件,内容为“17.901 -1.111 ...

  2. EasyUI datagrid添加右键菜单项

    js代码 //动态加载数据表格 function InitData() { $('#grid').datagrid({ url: '/Home/Query?r=' + Math.random(), / ...

  3. 关于 JavaScript 中一个小细节问题 (在控制台中直接 {Name:'王尼玛',Age:20} 对象报错问题)

    在 Chrome 浏览器,大家可能遇到这样一个小问题. 随便输入一个 Object 对象  ,比如 {Name:'王尼玛',Age:20} ,将会报错.之前,也从来没去考虑过到底是为啥原因. 今天,刚 ...

  4. MEF 编程指南(八):过滤目录

    当使用子容器的时候,基于特定的标准(Specific Criteria)过滤目录是很必要的.比如,基于部件构造策略的过滤器是很常见的.下面的代码片段演示了如何构建的特殊途径(Particular Ap ...

  5. Swift学习笔记三

    协议和扩展 在Objective-C中,协议是很常见也非常重要的一个特性,Swift中也保留了协议,语法略有变化. 用protocol关键字声明一个协议: protocol ExampleProtoc ...

  6. Html+jquery mobile

    打开VS 2013,选择[文件]-[新建]-[项目] 选择框架为.NET Framework4-[ASP.NET MVC4 Web应用程序],点击[确定] 选择[基本],点击[确定] 创建的MVC的项 ...

  7. C# Process 类的思考

    在这里,我先给自己留个印象 下面我们用C#实现一个调用Dos命令的小程序,让大家对系统进程能有个直观的了解.要使用Process类,首先要引入System.Diagnostic命名空间,然后定义一个新 ...

  8. CSS里的单位

    CSS中预设了16种颜色以及16种颜色的衍生色,这16种颜色是CSS规范推荐的.并且一些主流的浏览器都可以识别.例如以下表所看到的: 十六进制颜色是最经常使用的定义方式.它的基本格式为#RRGGBB, ...

  9. 【每日一摩斯】-Index Skip Scan Feature (212391.1)

    INDEX Skip Scan,也就是索引快速扫描,一般是指谓词中不带复合索引第一列,但扫描索引块要快于扫描表的数据块,此时CBO会选择INDEX SS的方式. 官方讲的,这个概念也好理解,如果将复合 ...

  10. Eclipse 环境下安装PhoneGap开发插件

    phoneGap开发跨所有移动平台软件已经成为未来移动终端开发的总趋势,如何在大家所熟悉的Eclipse IDE中快速安装PhoneGap开发插件,介绍如下: 点击help——>install ...