SlideShare a Scribd company logo
.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

More Related Content

What's hot

Data Manipulation Language
Data Manipulation LanguageData Manipulation Language
Data Manipulation Language
Jas Singh Bhasin
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
Venkata Sreeram
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Dharita Chokshi
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
Database Relationships
Database RelationshipsDatabase Relationships
Database Relationships
wmassie
 
Distributed database
Distributed databaseDistributed database
Distributed database
ReachLocal Services India
 
Data Dictionary
Data DictionaryData Dictionary
Data Dictionary
Vishal Anand
 
Concurrency Control in Database Management System
Concurrency Control in Database Management SystemConcurrency Control in Database Management System
Concurrency Control in Database Management System
Janki Shah
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Multiversion Concurrency Control Techniques
Multiversion Concurrency Control TechniquesMultiversion Concurrency Control Techniques
Multiversion Concurrency Control Techniques
Raj vardhan
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
NITISH KUMAR
 
Acid properties
Acid propertiesAcid properties
Acid properties
Abhilasha Lahigude
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
process control block
process control blockprocess control block
process control block
Vikas SHRIVASTAVA
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Process management os concept
Process management os conceptProcess management os concept
Process management os concept
priyadeosarkar91
 
SQL Views
SQL ViewsSQL Views
DISTRIBUTED DATABASE WITH RECOVERY TECHNIQUES
DISTRIBUTED DATABASE WITH RECOVERY TECHNIQUESDISTRIBUTED DATABASE WITH RECOVERY TECHNIQUES
DISTRIBUTED DATABASE WITH RECOVERY TECHNIQUES
AAKANKSHA JAIN
 
Database Management System Introduction
Database Management System IntroductionDatabase Management System Introduction
Database Management System Introduction
Smriti Jain
 
Triggers
TriggersTriggers
Triggers
Pooja Dixit
 

What's hot (20)

Data Manipulation Language
Data Manipulation LanguageData Manipulation Language
Data Manipulation Language
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
Database Relationships
Database RelationshipsDatabase Relationships
Database Relationships
 
Distributed database
Distributed databaseDistributed database
Distributed database
 
Data Dictionary
Data DictionaryData Dictionary
Data Dictionary
 
Concurrency Control in Database Management System
Concurrency Control in Database Management SystemConcurrency Control in Database Management System
Concurrency Control in Database Management System
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Multiversion Concurrency Control Techniques
Multiversion Concurrency Control TechniquesMultiversion Concurrency Control Techniques
Multiversion Concurrency Control Techniques
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
Acid properties
Acid propertiesAcid properties
Acid properties
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
process control block
process control blockprocess control block
process control block
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Process management os concept
Process management os conceptProcess management os concept
Process management os concept
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
DISTRIBUTED DATABASE WITH RECOVERY TECHNIQUES
DISTRIBUTED DATABASE WITH RECOVERY TECHNIQUESDISTRIBUTED DATABASE WITH RECOVERY TECHNIQUES
DISTRIBUTED DATABASE WITH RECOVERY TECHNIQUES
 
Database Management System Introduction
Database Management System IntroductionDatabase Management System Introduction
Database Management System Introduction
 
Triggers
TriggersTriggers
Triggers
 

Similar to Memory Management & Garbage Collection

Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
Roman Atachiants
 
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
Attila 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 4
aminmesbahi
 
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 Collection
Haribabu 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 performance
Codemotion
 
Beirut Java User Group JVM presentation
Beirut Java User Group JVM presentationBeirut Java User Group JVM presentation
Beirut Java User Group JVM presentation
Mahmoud Anouti
 
Jvm lecture
Jvm lectureJvm lecture
Jvm lecture
sdslnmd
 
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
Ernesto Arroyo Ron
 
GC in C#
GC in C#GC in C#
GC in C#
Kamal1997
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
Somya 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 Java
Abhishek Asthana
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
osa_ora
 
Hyperloglog Lightning Talk
Hyperloglog Lightning TalkHyperloglog Lightning Talk
Hyperloglog Lightning Talk
Simon Prickett
 
Garbage collection 介紹
Garbage collection 介紹Garbage collection 介紹
Garbage collection 介紹
kao kuo-tung
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
Mudit Gupta
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
Alex 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, Twitter
Lucidworks
 
Kubernetes Walk Through from Technical View
Kubernetes Walk Through from Technical ViewKubernetes Walk Through from Technical View
Kubernetes Walk Through from Technical View
Lei (Harry) Zhang
 

Similar to 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
 

More from Abhishek Sur

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

More from 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
 

Recently uploaded

High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
DianaGray10
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
alexjohnson7307
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
Google Developer Group - Harare
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
Ivanti
 
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptxMAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
janagijoythi
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
maigasapphire
 
Feature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptxFeature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptx
ssuser1915fe1
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
Safe Software
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
bellared2
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 

Recently uploaded (20)

High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
 
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptxMAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
 
Feature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptxFeature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptx
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 

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