`
mybwu_com
  • 浏览: 178415 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Heap And Stack -- Part1

 
阅读更多

Stack And Heap

PART 1

The Stack is care aboutwhat's executing in our code (beingcalled). The Heap is Care Aboutobjects created.

Think of the Stack as a series of boxes stacked one on top of the next. Wekeep track of what's going on in ourapplication by stacking another box on top every time we call a method (calleda Frame). We can only use what's in the top box on the stack. Whenwe're done with the top box (the method is done executing) we throw it away andproceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that itspurpose is to holdinformation (not keep track of execution most of the time) so anything inour Heap can be accessed atany time. With the Heap, there are no constraints as to what canbe accessed like in the stack.



The
Stack is maintained by system thread . Whenthe top box is no longer used, it's thrown out. The Heap, is maintained by GC - which deals with how to keepthe Heap clean .

What goes on the Stack and Heap?

We have four main types of things we'll be putting inthe Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions.

Value Types:

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

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

Reference Types:

All the "things" declared with the types inthis list are Reference types (and inherit from System.Object... except, ofcourse, for object which is the System.Object object):

  • class
  • interface
  • delegate
  • object
  • string

Pointers:

The third type of "thing" to be put in ourmemory management scheme is a Reference to a Type. A Reference is referred to as a Pointer. The pointers are managedby the CommonLanguage Runtime (CLR). A Pointer(or Reference) is different than a Reference Type in that when we say somethingis a Reference Type is means we access it through a Pointer. A Pointer isa space in memory that points to another space in memory. A Pointer can both put in Stack and Heap . its value is either a memory address or null.


Instructions:

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

How is it decided what goeswhere?

Here are our two golden rules:

  1. A Reference Type always goes on the Heap

  2. Value Types and Pointers always go where theywere declared.

The Stack, as wementioned earlier, is responsible for the executionof our code (or what's been called). You can think of it asa thread"state" and each thread has its own stack. When call a method, thethread put instructions on the top of stack then executingand put the method's parameters on the thread stack. Then, as we go throughthe code and run into variables within the method they are placed on top of thestack.

Take the following method.

publicintAddFive(intpValue)
{
intresult;
result = pValue + 5;
returnresult;
}


Next, some thread is passed to the instructions to the AddFive()method which lives in our type's method table, a JIT compilation is performedif this is the first time we are hitting the method.


As the method executes, we need some memory forthe "result" variable and it is allocated on the stack.

The method finishes execution and our result isreturned.

step 1>Method instruction

step 2>Parameters

step 3>result


And all memory used bythe method is cleaned up by movinga pointer to the available memory address where AddFive() started and we godown to the previous method on the stack (not seen here).


In this example, our "result" variableis placed on the stack. As a matter of fact, every time a Value Type is declaredwithin the body of a method, it will be placed on the stack.

Now, Value Types are also sometimes placed on theHeap. Remember the rule, Value Typesalways go where they were declared. Well, if a Value Typeis declared outside of a method, but inside a Reference Type it will be placedwithin the Reference Type on the Heap.

Here's another example.

If we have the following MyInt class (which is aReference Type because it is a class):

publicclassMyInt
{
publicintMyValue;
}

and the following method is executing:

publicMyIntAddFive(intpValue)
{
MyInt result =
newMyInt();
result.MyValue = pValue + 5;
returnresult;
}

Just as before, the thread starts executing themethod and its parameters are placed on the thread's stack.


Because Result Type--MyInt is a Reference Type , So it is placed on the Heap and referenced by a Pointer on theStack.


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


we're left withan orphaned MyInt in the heap .(waiting GC executing )


This is where the Garbage Collection (GC) comesinto play. GC will find all objects in the Heap that are not beingaccessed by the main program and delete them. The GC will then reorganizeall the objects left in the Heap to make space and adjust all the Pointers tothese objects in both the Stack and the Heap. As you can imagine, thiscan be quite expensive in terms of performance, so now you can see why it canbe important to pay attention to what's in the Stack and Heap when trying towrite high-performance code.

When we areusing Reference Types, we're dealing with Pointers to the type, not the thing itself. When we're using Value Types, we're using the thingitself.

If we execute the following method:

publicintReturnValue()
{
intx =newint();
x = 3;
inty =newint();
y = x;
y = 4;

returnx;
}

The Memory is allocated :


so We Got x= 3

However, if we are using the MyInt class frombefore

publicclassMyInt
{
publicintMyValue;
}

and we are executing the following method:

publicintReturnValue2()
{
MyInt x =
newMyInt();
x.MyValue = 3;
MyInt y =
newMyInt();
y = x;
y.MyValue =4;
returnx.MyValue;
}

The Memory allocated :

So We Got x=4


reference :http://www.c-sharpcorner.com/UploadFile/rmcochran/chsarp_memory401152006094206AM/chsarp_memory4.aspx

分享到:
评论

相关推荐

    Understanding and Using C Pointers 原版pdf by Reese

    The stack and heap are areas of memory used to support functions and dynamic memory allocation, respectively. Pointers are complex enough to deserve more in-depth treatment. This book provides that ...

    深入java虚拟机(inside the java virtual machine)

    10 Stack and Local Variable Operations Pushing Constants Onto the Stack Generic Stack Operations Pushing Local Variables Onto the Stack Popping to Local Variables The wide Instruction Fibonacci ...

    EurekaLog_7.5.0.0_Enterprise

    1)..Important: Installation layout was changed. All packages now have version suffix (e.g. EurekaLogCore240.bpl). No files are copied to \bin folder of IDE. Run-time package (EurekaLogCore) is copied ...

    Selected.Topics.in.Cplusplus.15117

    C++ has stack memory and heap memory. You need to control where you want to put your objects. It has constructors and destructors. You need to know when and how they are called. Then it has multiple ...

    uCOS-II v2.52 在 STM32 上的移植

    EXPORT __user_initial_stackheap ================================ Then rebuild. Add retarget code in main.c : ================================================================ #ifdef ...

    Microsoft Codeview and Utilities User's Guide

    Information in this document is subject to change without notice and does not represent a commitment on the part of Microsoft Corporation. The software described in this document is furnished under a ...

    硬盘克隆幽灵

    bootIni..................-1 volumeLabel..............[] sectorsInUse.............133232 totalNonCopiedBytes......0 bytesToCopy..............0 bitmapClusters...........157 bitmapUsedBytes..........

    DOS下用的GHOST 11.0.2.1573 版本(很好用的哦)

    pagefileSys..............-1 bootIni..................-1 volumeLabel..............[] sectorsInUse.............133568 totalNonCopiedBytes......0 bytesToCopy..............0 bitmapClusters............

    BobBuilder_app

    This means that you do a binary search in the page list in log M time and get the value in O(1) time within a page. RaptorDB starts off by loading the page list and it is good to go from there and...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expressions Boolean Expressions Return Values Variable and Array ...

    python3.6.5参考手册 chm

    PEP 471 - os.scandir() function – a better and faster directory iterator PEP 475: Retry system calls failing with EINTR PEP 479: Change StopIteration handling inside generators PEP 485: A function...

    Microsoft Visual C# 2013 Step by Step,最新资料

    Your hands-on guide to Visual C# fundamentals Expand your expertise—and teach yourself the fundamentals of Microsoft Visual C# 2013. If you have previous ...Using the stack and the heap 197 vu Contents

    vxworks_kernel_programmers_guide_6.9

    PART I: CORE TECHNOLOGIES 1 Overview ...................................................................................................... 3 1.1 Introduction ............................................

    千方百计笔试题大全

    11、heap 和stack 有什么区别? 9 12、Math.round(11.5) 等于多少? Math.round(-11.5)等于多少? 9 13、swtich 是否能作用在byte 上,是否能作用在long 上,是否能作用在String上? 9 14、编程题: 用最有效率的方法算...

    java面试宝典

    11、heap 和stack 有什么区别? 9 12、Math.round(11.5) 等于多少? Math.round(-11.5)等于多少? 9 13、swtich 是否能作用在byte 上,是否能作用在long 上,是否能作用在String上? 9 14、编程题: 用最有效率的方法算...

Global site tag (gtag.js) - Google Analytics