SlideShare une entreprise Scribd logo
1  sur  42
.NET Memory Management




         KolkataGeeks    1
• To perform efficient memory manipulation in
  performance critical system, we need to have
  a    good    understanding     of   memory
  management.




                    KolkataGeeks             2
Value Data Types
• The mapping from memory address seen by
  our program to the actual location in
  hardware memory is fully managed by
  Windows using a system known as "Virtual
  Adressing".
• Each process on a 32-bit processor sees 4-GB
  of available memory.


                    KolkataGeeks             3
• This 4GB of memory is called as “Virtual
  Address space or Virtual Memory”.
• Stack is an area, inside Virtual Memory.
• 1. It stores values data types.
• 2. Stack is used to hold a copy of any
  parameters passed to the method.



                     KolkataGeeks            4
KolkataGeeks   5
KolkataGeeks   6
• A stack pointer is a variable maintained by the
  Operating System.
• When our program first starts running, the stack
  pointer will point to just past the end of the block of
  memory that is reserved for the stack. The stack
  actually fills downward from high memory addresses
  to low memory addresses.
• The stack pointer is adjusted according to the data
  put on it.
• It always points to just past the next free location.


                         KolkataGeeks                   7
Reference Data Types
• Often we need to use a method to allocate memory
  for storing data and keeping that data available long
  after that method has exited.
• Whenever storage space is requested with the new
  operator i.e., for all reference types, such cases
  arises.
• Here before proceeding, I need to explain the term
  Managed Heap.



                        KolkataGeeks                  8
• The Managed Heap is another area of
  memory, from the processors available 4 GB.
• The new operator creates an object. This
  operator first confirms about the region
  present in the managed heap. If there is
  sufficient space, the pointer points to the
  object in the heap. And the new operator
  returns the address of the object.

                    KolkataGeeks            9
• Suppose there are 2 objects in the managed heap. And the pointer
  is pointing NewSpacePtr. If a new request for allocation of
  memory comes, the heap adds the size of the new object to
  NewSpacePtr. If(Size ofnew object+NewSpacePtr)>end of address
  space, then the heap has no free space and the garbage collection
  must be started.


                                            Enough Space



                         NewSpacePtr

       Object Y
       Object X

     Managed Heap
                             KolkataGeeks                             10
• When the pointer NewSpacePtr is pointing to 300, if
  any new object creation request comes, it will calculate
  the size of the address space. And it will ultimately call
  GC.



                                      Call GC!

                     310

                                        NewSpacePtr
          Object Z         300

          Object Y
                           200
          Object X         100

        Managed Heap
                                 KolkataGeeks                  11
Contains objects that are
         85,000 bytes larger


Large
Object
Heap

                             Managed
                              Heap
Small
Object
Heap         <85,000 bytes


                    KolkataGeeks       12
• The following code explain the working of heap and memory
  allocation for reference data types:




                           KolkataGeeks                       13
• Line 1
At first I have declared a Speaker reference called sp1.
Space for this is allocated in the stack. sp1 reference
takes up 4 bytes, to hold the address at which a
speaker object will be stored.

• Line 2
• Allocates memory on the heap to store a Speaker
  object.
• It sets the value of the variable sp1 to the address of
  the memory it has allocated to the new speaker
  object.

                         KolkataGeeks                  14
KolkataGeeks   15
• Line 3
Declares a Speaker reference.
Instantiates a MVPSpeaker object.




                            KolkataGeeks   16
Garbage Collection
• Garbage Collector removes all those objects from the heap
  that are no longer referenced. Hence, after GC runs, objects
  and free space are scattered in the heap.
• If this memory is allowed to be kept in this way, the runtime
  will have to search the heap, for a block of memory, in order
  to create a new object.
• Luckily, .Net GC doesn’t keep the heap like this. It compacts
  the heap by removing all remaining objects to form one
  continuous block of memory.
• When the objects have moved, their references are to be
  updated in the stack. This work is also handled by the garbage
  collector.

                            KolkataGeeks                      17
Advantages of Managed Heap
• In order to put data into the managed heap,
  the value of the heap pointer is needed to be
  read. Hence, under .NET, instantiating an
  object is much faster.
• Accessing objects tend to be faster too. The
  reason is the objects are compacted towards
  the same area of memory, on the heap.


                     KolkataGeeks             18
GC Generations




     KolkataGeeks   19
• The Garbage Collector performs a collection on generation 0,
   only when generation 0 is full.
•      This situation occurs when a request for creation of new
   object is made, and there is no sufficient memory to allocate
   for that object.
• This whole process is enhancing the performance of our
   application:
a. Younger objects are collected by the GC.
b. If these younger objects reside next to each other in the
    heap, then the garbage collection process will be faster.
c. If the related objects are residing next to each other, in the
    heap, the program execution will be faster.




                             KolkataGeeks                      20
How to free unmanaged resources
• We don’t worry about the unused objects, because GC frees
   memory as required. But unfortunately, GC does not know
   how to free unmanaged resources (ie., file handlers, database
   connections, network connections, etc).
• Hence, we are required to make provisions, so that
   unmanaged resources are released when an object of the
   class is destroyed.
• So while defining a class, we have to:
a. Declare a destructor as a member of a class.
b. Implement IDisposable Interface in our class.




                            KolkataGeeks                       21
Destructors
 • GC call the destructor of an
   object, before destroying it. The
   syntax for a destructor is given
   beside.
 • On compilation, the beside code
   gets     translated     into  the
   equivalent of a Finalize()
   method, which ensures that the
   Finalize() is executed.


     KolkataGeeks                 22
Code equivalent to the Finalize()
             • The following code, shows the C# code
               equivalent to the IL generated by the
               compiler for the ~abc destructor.
             • Here the method calls Finalize on its
               parent type and the parent type will call
               Finalize on its parent type.
             • In this way, the whole hierarchy of our
               object is destroyed.
             • So, we should have a destructor for our
               class, only if it is necessary, as on calling
               Finalize, GC puts the objects in the
               finalization queue to implement Finalize.
               And all these affects performance.




              KolkataGeeks                                23
Pictorial representation of Finalization Process




                     KolkataGeeks                  24
Finalization takes more time
• Objects that do not have a destructor are removed from
   memory in one pass of the garbage collector.
• Objects that have destructors requires 2 passes to be
   destroyed.
a. The first pass calls the destructor but doesn’t removes the
    object.
b. The second pass, destroys the object.
c. The .NET runtime, uses a single thread to execute the
    Finalize() method of all objects. This thread runs with high
    priority, and if many components need finalization, this
    thread will block threads with a lower priority from
    executing.

                            KolkataGeeks                      25
Disadvantages of Destructor

• Due to the way, the garbage collector works, it is not possible
  to know when an object’s destructor will actually execute.
• Just for this reason, we can’t place any code n the destructor,
  that needs to be run at a certain time.
• We also don’t know the order in which the objects will be
  destroyed.
• Final removal of an object from memory gets delayed due to
  the implementation of a destructor.




                             KolkataGeeks                      26
IDisposable Interface
• The System.IDisposable interface is an alternative to a
  destructor.
• This interface provides a mechanism for freeing unmanaged
  resources. It defines a single method named Dispose(), which
  takes no parameters and returns void. Dispose() explicitly
  frees all unmanaged resources used directly by an object.




                           KolkataGeeks                     27
• In the following example,
                                          the Dispose() will definitely
                                          be called, because this time,
                                          I have kept it within finally
                                          block.
• If an exception arises on the
  Open(), the Dispose() will
  never be called, in this case.
  So it is better to put it in try
  catch block.




                                KolkataGeeks                         28
• Using statement of C#, calls Dispose() on objects that
  implement IDisposable Interface.




• The using statement, followed in brackets by a reference
  variable declaration and instantiation, will cause that variable
  to be scoped to the accompanying statement block. When
  that variable goes out of scope, its Dispose() method will be
  called automatically, even if an exception occurs. Dispose()
  will be called on all objects, implementing IDisposable
  Interface, on exiting the using block.


                             KolkataGeeks                       29
IDisposable and Destructor used together




                 KolkataGeeks              30
KolkataGeeks   31
• As Dispose(), has already cleaned the unused
  objects(managed and unmanaged resources), there are
  nothing for the destructor to clean.
• On calling SupressFinalize() means, the garbage collector
  considers that this object has no destructor at all.




                             KolkataGeeks                     32
Friend Assembly
• An assembly that can access another
  assembly's members, is called a friend
  assembly.
• Using Friend Assembly, we can access internal
  type or internal member of an assembly.
• Private types and Private members are
  inaccessible.
• To access internal type or internal member of
  an assembly, we have to use InternalsVisibleTo
  attribute.

                     KolkataGeeks                  33
Friend Assembly




     KolkataGeeks   34
• Compile Class1.cs from the command prompt.
• And build the ClassLibrary2 also.




                   KolkataGeeks            35
Here we are referencing ClassLibrary2.




                KolkataGeeks             36
• As ClassLibrary2.Class1 has mentioned frnd_B
  within InternalsVisibleTo attribute, only this
  can access internal types and internals
  members of ClassLibrary2.Class1 .




                     KolkataGeeks                  37
• Frnd_B.exe is created in the
  D:frndClassLibrary2.
• This .exe is a friend of ClassLibrary2.dll




                       KolkataGeeks            38
• On executing frnd_B.exe, we get this output:




                     KolkataGeeks                39
GAC And Versioning
• If we change an assembly’s AssemblyVersion, a
  new identity of it is created. Suppose I am writing
  an assembly, strongly signed and assigned in the
  GAC with its version “1.0.0.0”. After sometime, I
  am modifying it, now its version is “1.0.0.1”.
  Reinstalling it in GAC. Now GAC will store two
  different versions of assembly.
• The benefits are:
• We can choose the version of the assembly. Which
  I want to use.
• Any existing application won’t get crushed,
  because older version of assembly still exists.

                        KolkataGeeks                    40
• This is called side-by-side execution. Side-
  by-Side execution prevents “DLL hell”
  that used to occur when any shared
  assembly gets updated and applications
  designed for the older version might stop
  working.



                    KolkataGeeks                 41
KolkataGeeks   42

Contenu connexe

Tendances

Transaction management DBMS
Transaction  management DBMSTransaction  management DBMS
Transaction management DBMSMegha Patel
 
Relational algebra ppt
Relational algebra pptRelational algebra ppt
Relational algebra pptGirdharRatne
 
Distributed Query Processing
Distributed Query ProcessingDistributed Query Processing
Distributed Query ProcessingMythili Kannan
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignHaitham El-Ghareeb
 
CS9222 Advanced Operating System
CS9222 Advanced Operating SystemCS9222 Advanced Operating System
CS9222 Advanced Operating SystemKathirvel Ayyaswamy
 
Disk Scheduling Algorithm in Operating System
Disk Scheduling Algorithm in Operating SystemDisk Scheduling Algorithm in Operating System
Disk Scheduling Algorithm in Operating SystemMeghaj Mallick
 
blackboard architecture
blackboard architectureblackboard architecture
blackboard architectureNguyễn Ngân
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocksJothi Lakshmi
 
Query processing and optimization (updated)
Query processing and optimization (updated)Query processing and optimization (updated)
Query processing and optimization (updated)Ravinder Kamboj
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionBipul Chandra Kar
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbmsshekhar1991
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxvishal choudhary
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Overview of UML Diagrams
Overview of UML DiagramsOverview of UML Diagrams
Overview of UML DiagramsManish Kumar
 

Tendances (20)

Transaction management DBMS
Transaction  management DBMSTransaction  management DBMS
Transaction management DBMS
 
Class diagrams
Class diagramsClass diagrams
Class diagrams
 
Relational algebra ppt
Relational algebra pptRelational algebra ppt
Relational algebra ppt
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Distributed Query Processing
Distributed Query ProcessingDistributed Query Processing
Distributed Query Processing
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 
CS9222 Advanced Operating System
CS9222 Advanced Operating SystemCS9222 Advanced Operating System
CS9222 Advanced Operating System
 
Chapter 7 - Deadlocks
Chapter 7 - DeadlocksChapter 7 - Deadlocks
Chapter 7 - Deadlocks
 
Disk Scheduling Algorithm in Operating System
Disk Scheduling Algorithm in Operating SystemDisk Scheduling Algorithm in Operating System
Disk Scheduling Algorithm in Operating System
 
blackboard architecture
blackboard architectureblackboard architecture
blackboard architecture
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocks
 
Code generation
Code generationCode generation
Code generation
 
Query processing
Query processingQuery processing
Query processing
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithm
 
Query processing and optimization (updated)
Query processing and optimization (updated)Query processing and optimization (updated)
Query processing and optimization (updated)
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbms
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Overview of UML Diagrams
Overview of UML DiagramsOverview of UML Diagrams
Overview of UML Diagrams
 

Similaire à Memory Management & Garbage Collection

Everything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @TwitterEverything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @TwitterAttila Szegedi
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4aminmesbahi
 
Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)Techizzaa
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionHaribabu Nandyal Padmanaban
 
.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup
 
Unity - Internals: memory and performance
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performanceCodemotion
 
Beirut Java User Group JVM presentation
Beirut Java User Group JVM presentationBeirut Java User Group JVM presentation
Beirut Java User Group JVM presentationMahmoud Anouti
 
Jvm lecture
Jvm lectureJvm lecture
Jvm lecturesdslnmd
 
Java Garbage Collector and The Memory Model
Java Garbage Collector and The Memory ModelJava Garbage Collector and The Memory Model
Java Garbage Collector and The Memory ModelErnesto Arroyo Ron
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionSomya Bagai
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAbhishek Asthana
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuningosa_ora
 
Hyperloglog Lightning Talk
Hyperloglog Lightning TalkHyperloglog Lightning Talk
Hyperloglog Lightning TalkSimon Prickett
 
Garbage collection 介紹
Garbage collection 介紹Garbage collection 介紹
Garbage collection 介紹kao kuo-tung
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionMudit Gupta
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Search at Twitter: Presented by Michael Busch, Twitter
Search at Twitter: Presented by Michael Busch, TwitterSearch at Twitter: Presented by Michael Busch, Twitter
Search at Twitter: Presented by Michael Busch, TwitterLucidworks
 
Kubernetes Walk Through from Technical View
Kubernetes Walk Through from Technical ViewKubernetes Walk Through from Technical View
Kubernetes Walk Through from Technical ViewLei (Harry) Zhang
 

Similaire à Memory Management & Garbage Collection (20)

Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Everything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @TwitterEverything I Ever Learned About JVM Performance Tuning @Twitter
Everything I Ever Learned About JVM Performance Tuning @Twitter
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4
 
Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage Collection
 
.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves
 
Unity - Internals: memory and performance
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performance
 
Beirut Java User Group JVM presentation
Beirut Java User Group JVM presentationBeirut Java User Group JVM presentation
Beirut Java User Group JVM presentation
 
Jvm lecture
Jvm lectureJvm lecture
Jvm lecture
 
Java Garbage Collector and The Memory Model
Java Garbage Collector and The Memory ModelJava Garbage Collector and The Memory Model
Java Garbage Collector and The Memory Model
 
GC in C#
GC in C#GC in C#
GC in C#
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in Java
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Hyperloglog Lightning Talk
Hyperloglog Lightning TalkHyperloglog Lightning Talk
Hyperloglog Lightning Talk
 
Garbage collection 介紹
Garbage collection 介紹Garbage collection 介紹
Garbage collection 介紹
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Search at Twitter: Presented by Michael Busch, Twitter
Search at Twitter: Presented by Michael Busch, TwitterSearch at Twitter: Presented by Michael Busch, Twitter
Search at Twitter: Presented by Michael Busch, Twitter
 
Kubernetes Walk Through from Technical View
Kubernetes Walk Through from Technical ViewKubernetes Walk Through from Technical View
Kubernetes Walk Through from Technical View
 

Plus de Abhishek Sur

Azure servicefabric
Azure servicefabricAzure servicefabric
Azure servicefabricAbhishek Sur
 
Building a bot with an intent
Building a bot with an intentBuilding a bot with an intent
Building a bot with an intentAbhishek Sur
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesAbhishek Sur
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to conceptsAbhishek Sur
 
Stream Analytics Service in Azure
Stream Analytics Service in AzureStream Analytics Service in Azure
Stream Analytics Service in AzureAbhishek Sur
 
Designing azure compute and storage infrastructure
Designing azure compute and storage infrastructureDesigning azure compute and storage infrastructure
Designing azure compute and storage infrastructureAbhishek Sur
 
Working with Azure Resource Manager Templates
Working with Azure Resource Manager TemplatesWorking with Azure Resource Manager Templates
Working with Azure Resource Manager TemplatesAbhishek Sur
 
F12 debugging in Ms edge
F12 debugging in Ms edgeF12 debugging in Ms edge
F12 debugging in Ms edgeAbhishek Sur
 
Mobile Services for Windows Azure
Mobile Services for Windows AzureMobile Services for Windows Azure
Mobile Services for Windows AzureAbhishek Sur
 
Service bus to build Bridges
Service bus to build BridgesService bus to build Bridges
Service bus to build BridgesAbhishek Sur
 
Windows azure pack overview
Windows azure pack overviewWindows azure pack overview
Windows azure pack overviewAbhishek Sur
 
AMicrosoft azure hyper v recovery manager overview
AMicrosoft azure hyper v recovery manager overviewAMicrosoft azure hyper v recovery manager overview
AMicrosoft azure hyper v recovery manager overviewAbhishek Sur
 
Di api di server b1 ws
Di api di server b1 wsDi api di server b1 ws
Di api di server b1 wsAbhishek Sur
 
Integrating cortana with wp8 app
Integrating cortana with wp8 appIntegrating cortana with wp8 app
Integrating cortana with wp8 appAbhishek Sur
 
Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performanceAbhishek Sur
 
Introduction to XAML and its features
Introduction to XAML and its featuresIntroduction to XAML and its features
Introduction to XAML and its featuresAbhishek Sur
 
SQL Server2012 Enhancements
SQL Server2012 EnhancementsSQL Server2012 Enhancements
SQL Server2012 EnhancementsAbhishek Sur
 
Dev days Visual Studio 2012 Enhancements
Dev days Visual Studio 2012 EnhancementsDev days Visual Studio 2012 Enhancements
Dev days Visual Studio 2012 EnhancementsAbhishek Sur
 
Hidden Facts of .NET Language Gems
Hidden Facts of .NET Language GemsHidden Facts of .NET Language Gems
Hidden Facts of .NET Language GemsAbhishek Sur
 

Plus de Abhishek Sur (20)

Azure servicefabric
Azure servicefabricAzure servicefabric
Azure servicefabric
 
Building a bot with an intent
Building a bot with an intentBuilding a bot with an intent
Building a bot with an intent
 
Code review
Code reviewCode review
Code review
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and Features
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to concepts
 
Stream Analytics Service in Azure
Stream Analytics Service in AzureStream Analytics Service in Azure
Stream Analytics Service in Azure
 
Designing azure compute and storage infrastructure
Designing azure compute and storage infrastructureDesigning azure compute and storage infrastructure
Designing azure compute and storage infrastructure
 
Working with Azure Resource Manager Templates
Working with Azure Resource Manager TemplatesWorking with Azure Resource Manager Templates
Working with Azure Resource Manager Templates
 
F12 debugging in Ms edge
F12 debugging in Ms edgeF12 debugging in Ms edge
F12 debugging in Ms edge
 
Mobile Services for Windows Azure
Mobile Services for Windows AzureMobile Services for Windows Azure
Mobile Services for Windows Azure
 
Service bus to build Bridges
Service bus to build BridgesService bus to build Bridges
Service bus to build Bridges
 
Windows azure pack overview
Windows azure pack overviewWindows azure pack overview
Windows azure pack overview
 
AMicrosoft azure hyper v recovery manager overview
AMicrosoft azure hyper v recovery manager overviewAMicrosoft azure hyper v recovery manager overview
AMicrosoft azure hyper v recovery manager overview
 
Di api di server b1 ws
Di api di server b1 wsDi api di server b1 ws
Di api di server b1 ws
 
Integrating cortana with wp8 app
Integrating cortana with wp8 appIntegrating cortana with wp8 app
Integrating cortana with wp8 app
 
Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performance
 
Introduction to XAML and its features
Introduction to XAML and its featuresIntroduction to XAML and its features
Introduction to XAML and its features
 
SQL Server2012 Enhancements
SQL Server2012 EnhancementsSQL Server2012 Enhancements
SQL Server2012 Enhancements
 
Dev days Visual Studio 2012 Enhancements
Dev days Visual Studio 2012 EnhancementsDev days Visual Studio 2012 Enhancements
Dev days Visual Studio 2012 Enhancements
 
Hidden Facts of .NET Language Gems
Hidden Facts of .NET Language GemsHidden Facts of .NET Language Gems
Hidden Facts of .NET Language Gems
 

Dernier

SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Dernier (20)

SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Memory Management & Garbage Collection

  • 1. .NET Memory Management KolkataGeeks 1
  • 2. • To perform efficient memory manipulation in performance critical system, we need to have a good understanding of memory management. KolkataGeeks 2
  • 3. Value Data Types • The mapping from memory address seen by our program to the actual location in hardware memory is fully managed by Windows using a system known as "Virtual Adressing". • Each process on a 32-bit processor sees 4-GB of available memory. KolkataGeeks 3
  • 4. • This 4GB of memory is called as “Virtual Address space or Virtual Memory”. • Stack is an area, inside Virtual Memory. • 1. It stores values data types. • 2. Stack is used to hold a copy of any parameters passed to the method. KolkataGeeks 4
  • 7. • A stack pointer is a variable maintained by the Operating System. • When our program first starts running, the stack pointer will point to just past the end of the block of memory that is reserved for the stack. The stack actually fills downward from high memory addresses to low memory addresses. • The stack pointer is adjusted according to the data put on it. • It always points to just past the next free location. KolkataGeeks 7
  • 8. Reference Data Types • Often we need to use a method to allocate memory for storing data and keeping that data available long after that method has exited. • Whenever storage space is requested with the new operator i.e., for all reference types, such cases arises. • Here before proceeding, I need to explain the term Managed Heap. KolkataGeeks 8
  • 9. • The Managed Heap is another area of memory, from the processors available 4 GB. • The new operator creates an object. This operator first confirms about the region present in the managed heap. If there is sufficient space, the pointer points to the object in the heap. And the new operator returns the address of the object. KolkataGeeks 9
  • 10. • Suppose there are 2 objects in the managed heap. And the pointer is pointing NewSpacePtr. If a new request for allocation of memory comes, the heap adds the size of the new object to NewSpacePtr. If(Size ofnew object+NewSpacePtr)>end of address space, then the heap has no free space and the garbage collection must be started. Enough Space NewSpacePtr Object Y Object X Managed Heap KolkataGeeks 10
  • 11. • When the pointer NewSpacePtr is pointing to 300, if any new object creation request comes, it will calculate the size of the address space. And it will ultimately call GC. Call GC! 310 NewSpacePtr Object Z 300 Object Y 200 Object X 100 Managed Heap KolkataGeeks 11
  • 12. Contains objects that are 85,000 bytes larger Large Object Heap Managed Heap Small Object Heap <85,000 bytes KolkataGeeks 12
  • 13. • The following code explain the working of heap and memory allocation for reference data types: KolkataGeeks 13
  • 14. • Line 1 At first I have declared a Speaker reference called sp1. Space for this is allocated in the stack. sp1 reference takes up 4 bytes, to hold the address at which a speaker object will be stored. • Line 2 • Allocates memory on the heap to store a Speaker object. • It sets the value of the variable sp1 to the address of the memory it has allocated to the new speaker object. KolkataGeeks 14
  • 16. • Line 3 Declares a Speaker reference. Instantiates a MVPSpeaker object. KolkataGeeks 16
  • 17. Garbage Collection • Garbage Collector removes all those objects from the heap that are no longer referenced. Hence, after GC runs, objects and free space are scattered in the heap. • If this memory is allowed to be kept in this way, the runtime will have to search the heap, for a block of memory, in order to create a new object. • Luckily, .Net GC doesn’t keep the heap like this. It compacts the heap by removing all remaining objects to form one continuous block of memory. • When the objects have moved, their references are to be updated in the stack. This work is also handled by the garbage collector. KolkataGeeks 17
  • 18. Advantages of Managed Heap • In order to put data into the managed heap, the value of the heap pointer is needed to be read. Hence, under .NET, instantiating an object is much faster. • Accessing objects tend to be faster too. The reason is the objects are compacted towards the same area of memory, on the heap. KolkataGeeks 18
  • 19. GC Generations KolkataGeeks 19
  • 20. • The Garbage Collector performs a collection on generation 0, only when generation 0 is full. • This situation occurs when a request for creation of new object is made, and there is no sufficient memory to allocate for that object. • This whole process is enhancing the performance of our application: a. Younger objects are collected by the GC. b. If these younger objects reside next to each other in the heap, then the garbage collection process will be faster. c. If the related objects are residing next to each other, in the heap, the program execution will be faster. KolkataGeeks 20
  • 21. How to free unmanaged resources • We don’t worry about the unused objects, because GC frees memory as required. But unfortunately, GC does not know how to free unmanaged resources (ie., file handlers, database connections, network connections, etc). • Hence, we are required to make provisions, so that unmanaged resources are released when an object of the class is destroyed. • So while defining a class, we have to: a. Declare a destructor as a member of a class. b. Implement IDisposable Interface in our class. KolkataGeeks 21
  • 22. Destructors • GC call the destructor of an object, before destroying it. The syntax for a destructor is given beside. • On compilation, the beside code gets translated into the equivalent of a Finalize() method, which ensures that the Finalize() is executed. KolkataGeeks 22
  • 23. Code equivalent to the Finalize() • The following code, shows the C# code equivalent to the IL generated by the compiler for the ~abc destructor. • Here the method calls Finalize on its parent type and the parent type will call Finalize on its parent type. • In this way, the whole hierarchy of our object is destroyed. • So, we should have a destructor for our class, only if it is necessary, as on calling Finalize, GC puts the objects in the finalization queue to implement Finalize. And all these affects performance. KolkataGeeks 23
  • 24. Pictorial representation of Finalization Process KolkataGeeks 24
  • 25. Finalization takes more time • Objects that do not have a destructor are removed from memory in one pass of the garbage collector. • Objects that have destructors requires 2 passes to be destroyed. a. The first pass calls the destructor but doesn’t removes the object. b. The second pass, destroys the object. c. The .NET runtime, uses a single thread to execute the Finalize() method of all objects. This thread runs with high priority, and if many components need finalization, this thread will block threads with a lower priority from executing. KolkataGeeks 25
  • 26. Disadvantages of Destructor • Due to the way, the garbage collector works, it is not possible to know when an object’s destructor will actually execute. • Just for this reason, we can’t place any code n the destructor, that needs to be run at a certain time. • We also don’t know the order in which the objects will be destroyed. • Final removal of an object from memory gets delayed due to the implementation of a destructor. KolkataGeeks 26
  • 27. IDisposable Interface • The System.IDisposable interface is an alternative to a destructor. • This interface provides a mechanism for freeing unmanaged resources. It defines a single method named Dispose(), which takes no parameters and returns void. Dispose() explicitly frees all unmanaged resources used directly by an object. KolkataGeeks 27
  • 28. • In the following example, the Dispose() will definitely be called, because this time, I have kept it within finally block. • If an exception arises on the Open(), the Dispose() will never be called, in this case. So it is better to put it in try catch block. KolkataGeeks 28
  • 29. • Using statement of C#, calls Dispose() on objects that implement IDisposable Interface. • The using statement, followed in brackets by a reference variable declaration and instantiation, will cause that variable to be scoped to the accompanying statement block. When that variable goes out of scope, its Dispose() method will be called automatically, even if an exception occurs. Dispose() will be called on all objects, implementing IDisposable Interface, on exiting the using block. KolkataGeeks 29
  • 30. IDisposable and Destructor used together KolkataGeeks 30
  • 32. • As Dispose(), has already cleaned the unused objects(managed and unmanaged resources), there are nothing for the destructor to clean. • On calling SupressFinalize() means, the garbage collector considers that this object has no destructor at all. KolkataGeeks 32
  • 33. Friend Assembly • An assembly that can access another assembly's members, is called a friend assembly. • Using Friend Assembly, we can access internal type or internal member of an assembly. • Private types and Private members are inaccessible. • To access internal type or internal member of an assembly, we have to use InternalsVisibleTo attribute. KolkataGeeks 33
  • 34. Friend Assembly KolkataGeeks 34
  • 35. • Compile Class1.cs from the command prompt. • And build the ClassLibrary2 also. KolkataGeeks 35
  • 36. Here we are referencing ClassLibrary2. KolkataGeeks 36
  • 37. • As ClassLibrary2.Class1 has mentioned frnd_B within InternalsVisibleTo attribute, only this can access internal types and internals members of ClassLibrary2.Class1 . KolkataGeeks 37
  • 38. • Frnd_B.exe is created in the D:frndClassLibrary2. • This .exe is a friend of ClassLibrary2.dll KolkataGeeks 38
  • 39. • On executing frnd_B.exe, we get this output: KolkataGeeks 39
  • 40. GAC And Versioning • If we change an assembly’s AssemblyVersion, a new identity of it is created. Suppose I am writing an assembly, strongly signed and assigned in the GAC with its version “1.0.0.0”. After sometime, I am modifying it, now its version is “1.0.0.1”. Reinstalling it in GAC. Now GAC will store two different versions of assembly. • The benefits are: • We can choose the version of the assembly. Which I want to use. • Any existing application won’t get crushed, because older version of assembly still exists. KolkataGeeks 40
  • 41. • This is called side-by-side execution. Side- by-Side execution prevents “DLL hell” that used to occur when any shared assembly gets updated and applications designed for the older version might stop working. KolkataGeeks 41