What goes inside when you declare a variable?

Similar documents
Chapter 1 Getting Started

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

CA31-1K DIS. Pointers. TA: You Lu

Worksheet #4. Foundations of Programming Languages, WS 2014/15. December 4, 2014

References and pointers

Memory and C++ Pointers

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Introduction to Programming Using Java (98-388)

Run Time Environment

CS121/IS223. Object Reference Variables. Dr Olly Gotel

G Programming Languages - Fall 2012

A heap, a stack, a bottle and a rack. Johan Montelius HT2017

Pointers II. Class 31

In Java we have the keyword null, which is the value of an uninitialized reference type

Pointers, Arrays and Parameters

.Net Technologies. Components of.net Framework

COMP 524 Spring 2018 Midterm Thursday, March 1

5 When a program calls a function, in which type of data structure is memory allocated for the variables in that function?

Run-Time Environments/Garbage Collection

C++ Programming Lecture 4 Software Engineering Group

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

a data type is Types

Vector and Free Store (Pointers and Memory Allocation)

Short Notes of CS201

Writing Functions in C

CS201 - Introduction to Programming Glossary By

Fun facts about recursion

Introduction To C#.NET

Understand Computer Storage and Data Types

Programming II (CS300)

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

QUESTION BANK: INTRODUCTION TO PROGRAMMING (HCS102) a. Compare and contrast unboxing and widening using code snippets [10]

Data Structure Series

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

The Stack, Free Store, and Global Namespace

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Chapter 6 Introduction to Defining Classes

(3-2) Basics of a Stack. Instructor - Andrew S. O Fallon CptS 122 (January 26, 2018) Washington State University

THREADS: (abstract CPUs)

Introduction to C Language (M3-R )

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Programming Language Concepts Scoping. Janyl Jumadinova January 31, 2017

2. Introducing Classes

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Computer Science And Engineering

PES INSTITUTE OF TECHNOLOGY

Overview COMP Microprocessors and Embedded Systems. Lectures 18 : Pointers & Arrays in C/ Assembly

VARIABLES AND TYPES CITS1001

Algorithms & Data Structures

Advances in Programming Languages: Regions

HOT-Compilation: Garbage Collection

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java)

Towards Lean 4: Sebastian Ullrich 1, Leonardo de Moura 2.

Heap Arrays and Linked Lists. Steven R. Bagley

Chapter 17 vector and Free Store

Data Structure. Recitation IV

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Habanero Extreme Scale Software Research Project

Introduce C# as Object Oriented programming language. Explain, tokens,

Principles of Computer Science

1 Dynamic Memory continued: Memory Leaks

For instance, we can declare an array of five ints like this: int numbers[5];

Scope, Functions, and Storage Management

Assumptions. History

NCS 301 DATA STRUCTURE USING C

Today's Topics. CISC 458 Winter J.R. Cordy

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Incoming Exam. CS 201 Introduction to Pointers. What is a Pointer? Pointers and Addresses. High Speed Memory (RAM) Size of Variable Types.

POINTER AND ARRAY SUNU WIBIRAMA

Java Internals. Frank Yellin Tim Lindholm JavaSoft

CSE 142 Su 04 Computer Programming 1 - Java. Objects

The Java Programming Language

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

C#: framework overview and in-the-small features

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS201 Some Important Definitions

C11: Garbage Collection and Constructors

C Programming Basics II

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1

20 Most Important Java Programming Interview Questions. Powered by

C# Programming in the.net Framework

CS 231 Data Structures and Algorithms, Fall 2016

CS143 Final Fall 2009

vector and Free Store


New Concepts. Lab 7 Using Arrays, an Introduction

C++_ MARKS 40 MIN

Primitive Data and Objects

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CS61, Fall 2012 Section 2 Notes


Dynamic Data Structures (II)

Kakadu and Java. David Taubman, UNSW June 3, 2003

M1-R4: Programing and Problem Solving using C (JAN 2019)

Fundamentals of Programming Session 12

Transcription:

Stack, heap, value types, reference types, boxing, and unboxing 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. 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=4; // Line 2 int y=2; } //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 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 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 (http://msdn.microsoft.com/enus/library/f7dy01k1%28v=vs.110%29.aspx), 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. http://www.codeproject.com/articles/76153/six-important-net-concepts-stack-heap-value-types