SlideShare a Scribd company logo
1 of 17
Download to read offline
Memory
Management
In Go!
wednesday.is
2
Content
What we’ll be covering..
Memory Management
Restructure the structs
Garbage Collector
Stack
Heap
MemoryAllocation
MemoryAllocators
How to reduce Garbage
wednesday.is
Memory Management
Memory management is a method in the operating system to manage
operations between main memory and disk during process execution.
Importance of memory management: RAM is
fi
nite. If a program keeps on consuming
memory without freeing it, it will run out of memory and crash itself. Therefore, software
programs can’t just keep using RAM as they like, it will cause other programs and processes
to run out of memory. Due to importance of this, most programming languages (including Go)
provide ways to do automatic memory management.
We can achieve ef
fi
cient utilisation of memory by following a good memory
management.
wednesday.is
Memory Hierarchy
wednesday.is
Memory Management in Go
• The automatic memory allocation and automatic garbage collection will avoid many
lurking bugs.
• Providing ways to dynamically allocate portions of memory to programs at their
request, and free it for reuse when no longer needed.
Go is a language which supports automatic memory management, such as
automatic memory allocation and automatic garbage collection.
wednesday.is
Memory Allocations
• Static Allocation is what happens when you declare a global variable. Each global
variable de
fi
nes one block of space, of a
fi
xed size.The space is allocated once,
when your program is started, and is never freed.
• Automatic Allocation happens when you declare an automatic variable, such as a
function argument or a local variable. The space for an automatic variable is
allocated when the compound statement containing the declaration is entered, and
is freed when that compound statement is exited.
• Dynamic Allocation is a technique in which programs determine as they are
running where to store some information. We need dynamic allocation when the
amount of memory we need, or how long we continue to need it, depends on
factors that are not known before the program runs.
wednesday.is
Memory Allocators
• TCMalloc is faster than the glibc 2.3 malloc (available as a separate library called ptmalloc2).
• ptmalloc2 takes approximately 300 nanoseconds to execute a malloc.
• TCMalloc implementation takes approximately 50 nanoseconds for the same operation pair.
As Go doesn’
t use Malloc to get memory, but asks OS directly(via mmap), it has to
implement memory allocation and deallocation on its own(like Malloc does). Go’
s memory
allocator is originally based off TCMalloc (thread-cache memory allocation).
wednesday.is
Stack & Heap
Stack
It is used for static memory allocation and just like the
data structure.
It follows the last in
fi
rst out(LIFO) approach.
Typically, functional parameters and local variables
are allocated on the stack.
Nothing really moves physically when data is pushed on to
or popped o
ff
from a stack in memory. Only the values
stored in the memory managed by the stack are changed.
This makes the process of storing and retrieving data from the
stack very fast since there is no lookup required. We can just
store and retrieve data from the top most block on it.
Any data that is stored on the stack has to be
fi
nite and static.
This means the size of the data is known at compile time.
Memory management of the stack is simple and straightforward
and is done by the OS.
Heap
The name heap has nothing to do with the heap data structure.
Heap is used for dynamic memory allocation.
Whereas the stack only allows allocation and deallocation at the top,
programs can allocate or deallocate memory anywhere in a heap.
The program must return memory to the stack in the opposite
order of its allocation. But the program can return memory to the
heap in any order.
This means heap is more
fl
exible than the stack.
Pointers, arrays and big data structures are usually stored in Heap.
wednesday.is
Stack Vs Heap
Heap is slower compared to stack because the process of looking up data is more involved.
Heap can store more data than the stack.
Heap stores data with dynamic size; stack stores data with static size.
Heap is shared among threads of an application.
Heap is trickier to manage because of its dynamic nature.
Heap memory allocation isn’t as safe as stack memory allocation, because the data stored
in this space is accessible or visible to all threads.
Whenever a function is called, its variables get memory allocated on the stack. And
whenever the function call is over, the memory for the variables is de-allocated.
Heap memory allocation scheme does not provide automatic de-allocation. We need
to use a Garbage Collector to remove the unused objects in order to use the
memory e
ffi
ciently.
wednesday.is
Memory model, the Go way!
• Go allocates memory in two places: a global heap for dynamic allocations and a local stack for each
goroutine.
• In Go, each goroutine(thread) has its own stack. When we start a goroutine, we allocate a block of
memory to be used as that goroutine’s stack.
• A goroutine starts with 2 KB stack size which can grow and shrink as needed.
• Go prefers allocation on the stack.
• Stack allocation is cheaper because it only requires two CPU instructions: one to push onto the stack
for allocation, and another to release(pop) from the stack.
• Unfortunately not all data can use memory allocated on the stack. Stack allocation requires that the
lifetime and memory footprint of a variable can be determined at compile time.
• If it can’t be determined, a dynamic allocation onto the heap occurs at runtime.
• The Go compiler uses a process called escape analysis to
fi
nd objects whose lifetime is known at
compile-time and allocates them on the stack rather than in garbage collected heap memory.
wednesday.is
Garbage Collector
It is form of automatic memory management. The Garbage Collector
attempts to reclaim memory which was allocated by program, but is no longer
referenced.
Go’s garbage collector is a non-generational concurrent, tri-color mark
and sweep garbage collector.
Go’s garbage collection works in two phases, the mark phase, and sweep
phase. GC uses the tri-color algorithm to analyse the use of memory blocks.
This algorithm
fi
rst marks objects that are still being referenced as “alive”, and
in the next phase sweep frees the memory of objects that are not alive.
wednesday.is
You don’t have to collect your garbage,
but you can reduce your garbage.
Restructure your structs.
Reduce the number of long living objects.
Remove pointers within pointers.
Avoid unnecessary string/byte array allocations.
wednesday.is
Restructure the structs
wednesday.is
Why do we do restructure structs…?
While reading data, a modern Computer’s CPU’s internal data registers
can hold and process 64 bits. This is called the word size (It is usually 32 bits
or 64 bits).
When we don’t align our data to
fi
t word sizes, padding is added for
properly aligning
fi
elds in memory so that next
fi
eld can start at an o
ff
set
that’s multiple of a word size.
Thanks for your time..!
wednesday.is

More Related Content

Similar to Memory Management in Go: Stack, Heap & Garbage Collector

Internet of Things, TYBSC IT, Semester 5, Unit IV
Internet of Things, TYBSC IT, Semester 5, Unit IVInternet of Things, TYBSC IT, Semester 5, Unit IV
Internet of Things, TYBSC IT, Semester 5, Unit IVArti Parab Academics
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionMudit Gupta
 
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12sidg75
 
How to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidHow to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidSingsys Pte Ltd
 
Taming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust RewriteTaming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust RewriteScyllaDB
 
A kind of Algorithm that Extend MLC SSD Life Expectancy by 3 Folds
A kind of Algorithm that Extend MLC SSD Life Expectancy by 3 FoldsA kind of Algorithm that Extend MLC SSD Life Expectancy by 3 Folds
A kind of Algorithm that Extend MLC SSD Life Expectancy by 3 FoldsMay Lau
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK toolsHaribabu Nandyal Padmanaban
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTAkhilMishra50
 
Operating system Memory management
Operating system Memory management Operating system Memory management
Operating system Memory management Shashank Asthana
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performanceRoger Xia
 
Paging +Algorithem+Segmentation+memory management
Paging +Algorithem+Segmentation+memory managementPaging +Algorithem+Segmentation+memory management
Paging +Algorithem+Segmentation+memory managementkazim Hussain
 
memory managment on computer science.ppt
memory managment on computer science.pptmemory managment on computer science.ppt
memory managment on computer science.pptfootydigarse
 

Similar to Memory Management in Go: Stack, Heap & Garbage Collector (20)

Opetating System Memory management
Opetating System Memory managementOpetating System Memory management
Opetating System Memory management
 
Internet of Things, TYBSC IT, Semester 5, Unit IV
Internet of Things, TYBSC IT, Semester 5, Unit IVInternet of Things, TYBSC IT, Semester 5, Unit IV
Internet of Things, TYBSC IT, Semester 5, Unit IV
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
Garbage Collection, Tuning And Monitoring JVM In EBS 11i And R12
 
unit5_os (1).pptx
unit5_os (1).pptxunit5_os (1).pptx
unit5_os (1).pptx
 
How to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidHow to do Memory Optimizations in Android
How to do Memory Optimizations in Android
 
Taming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust RewriteTaming Go's Memory Usage — and Avoiding a Rust Rewrite
Taming Go's Memory Usage — and Avoiding a Rust Rewrite
 
Os unit 2
Os unit 2Os unit 2
Os unit 2
 
A kind of Algorithm that Extend MLC SSD Life Expectancy by 3 Folds
A kind of Algorithm that Extend MLC SSD Life Expectancy by 3 FoldsA kind of Algorithm that Extend MLC SSD Life Expectancy by 3 Folds
A kind of Algorithm that Extend MLC SSD Life Expectancy by 3 Folds
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Module 4 memory management
Module 4 memory managementModule 4 memory management
Module 4 memory management
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Memory Hierarchy
Memory HierarchyMemory Hierarchy
Memory Hierarchy
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
 
Operating system Memory management
Operating system Memory management Operating system Memory management
Operating system Memory management
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 
Paging +Algorithem+Segmentation+memory management
Paging +Algorithem+Segmentation+memory managementPaging +Algorithem+Segmentation+memory management
Paging +Algorithem+Segmentation+memory management
 
memory managment on computer science.ppt
memory managment on computer science.pptmemory managment on computer science.ppt
memory managment on computer science.ppt
 
Operating system
Operating systemOperating system
Operating system
 
Memory management
Memory managementMemory management
Memory management
 

More from Wednesday Solutions

Master iOS Performance Optimization with Instruments
Master iOS Performance Optimization with InstrumentsMaster iOS Performance Optimization with Instruments
Master iOS Performance Optimization with InstrumentsWednesday Solutions
 
What is React Concurrent Mode: A Walkthrough
What is React Concurrent Mode: A WalkthroughWhat is React Concurrent Mode: A Walkthrough
What is React Concurrent Mode: A WalkthroughWednesday Solutions
 
Create Basic 3D Scenes Using Three.js
Create Basic 3D Scenes Using Three.jsCreate Basic 3D Scenes Using Three.js
Create Basic 3D Scenes Using Three.jsWednesday Solutions
 
What is Temporal: Workflow & Cluster
What is Temporal: Workflow & ClusterWhat is Temporal: Workflow & Cluster
What is Temporal: Workflow & ClusterWednesday Solutions
 

More from Wednesday Solutions (8)

Error Handling in Express
Error Handling in ExpressError Handling in Express
Error Handling in Express
 
Master iOS Performance Optimization with Instruments
Master iOS Performance Optimization with InstrumentsMaster iOS Performance Optimization with Instruments
Master iOS Performance Optimization with Instruments
 
What is React Concurrent Mode: A Walkthrough
What is React Concurrent Mode: A WalkthroughWhat is React Concurrent Mode: A Walkthrough
What is React Concurrent Mode: A Walkthrough
 
Create Basic 3D Scenes Using Three.js
Create Basic 3D Scenes Using Three.jsCreate Basic 3D Scenes Using Three.js
Create Basic 3D Scenes Using Three.js
 
A Guide to Figma for Developers
A Guide to Figma for DevelopersA Guide to Figma for Developers
A Guide to Figma for Developers
 
What is Temporal: Workflow & Cluster
What is Temporal: Workflow & ClusterWhat is Temporal: Workflow & Cluster
What is Temporal: Workflow & Cluster
 
Vector Embedding using AI
Vector Embedding using AIVector Embedding using AI
Vector Embedding using AI
 
What is GraphQL: Best Practices
What is GraphQL: Best PracticesWhat is GraphQL: Best Practices
What is GraphQL: Best Practices
 

Recently uploaded

Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 

Recently uploaded (20)

Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 

Memory Management in Go: Stack, Heap & Garbage Collector

  • 2. 2 Content What we’ll be covering.. Memory Management Restructure the structs Garbage Collector Stack Heap MemoryAllocation MemoryAllocators How to reduce Garbage
  • 3. wednesday.is Memory Management Memory management is a method in the operating system to manage operations between main memory and disk during process execution. Importance of memory management: RAM is fi nite. If a program keeps on consuming memory without freeing it, it will run out of memory and crash itself. Therefore, software programs can’t just keep using RAM as they like, it will cause other programs and processes to run out of memory. Due to importance of this, most programming languages (including Go) provide ways to do automatic memory management. We can achieve ef fi cient utilisation of memory by following a good memory management.
  • 5. wednesday.is Memory Management in Go • The automatic memory allocation and automatic garbage collection will avoid many lurking bugs. • Providing ways to dynamically allocate portions of memory to programs at their request, and free it for reuse when no longer needed. Go is a language which supports automatic memory management, such as automatic memory allocation and automatic garbage collection.
  • 6. wednesday.is Memory Allocations • Static Allocation is what happens when you declare a global variable. Each global variable de fi nes one block of space, of a fi xed size.The space is allocated once, when your program is started, and is never freed. • Automatic Allocation happens when you declare an automatic variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited. • Dynamic Allocation is a technique in which programs determine as they are running where to store some information. We need dynamic allocation when the amount of memory we need, or how long we continue to need it, depends on factors that are not known before the program runs.
  • 7. wednesday.is Memory Allocators • TCMalloc is faster than the glibc 2.3 malloc (available as a separate library called ptmalloc2). • ptmalloc2 takes approximately 300 nanoseconds to execute a malloc. • TCMalloc implementation takes approximately 50 nanoseconds for the same operation pair. As Go doesn’ t use Malloc to get memory, but asks OS directly(via mmap), it has to implement memory allocation and deallocation on its own(like Malloc does). Go’ s memory allocator is originally based off TCMalloc (thread-cache memory allocation).
  • 9. Stack It is used for static memory allocation and just like the data structure. It follows the last in fi rst out(LIFO) approach. Typically, functional parameters and local variables are allocated on the stack. Nothing really moves physically when data is pushed on to or popped o ff from a stack in memory. Only the values stored in the memory managed by the stack are changed. This makes the process of storing and retrieving data from the stack very fast since there is no lookup required. We can just store and retrieve data from the top most block on it. Any data that is stored on the stack has to be fi nite and static. This means the size of the data is known at compile time. Memory management of the stack is simple and straightforward and is done by the OS.
  • 10. Heap The name heap has nothing to do with the heap data structure. Heap is used for dynamic memory allocation. Whereas the stack only allows allocation and deallocation at the top, programs can allocate or deallocate memory anywhere in a heap. The program must return memory to the stack in the opposite order of its allocation. But the program can return memory to the heap in any order. This means heap is more fl exible than the stack. Pointers, arrays and big data structures are usually stored in Heap.
  • 11. wednesday.is Stack Vs Heap Heap is slower compared to stack because the process of looking up data is more involved. Heap can store more data than the stack. Heap stores data with dynamic size; stack stores data with static size. Heap is shared among threads of an application. Heap is trickier to manage because of its dynamic nature. Heap memory allocation isn’t as safe as stack memory allocation, because the data stored in this space is accessible or visible to all threads. Whenever a function is called, its variables get memory allocated on the stack. And whenever the function call is over, the memory for the variables is de-allocated. Heap memory allocation scheme does not provide automatic de-allocation. We need to use a Garbage Collector to remove the unused objects in order to use the memory e ffi ciently.
  • 12. wednesday.is Memory model, the Go way! • Go allocates memory in two places: a global heap for dynamic allocations and a local stack for each goroutine. • In Go, each goroutine(thread) has its own stack. When we start a goroutine, we allocate a block of memory to be used as that goroutine’s stack. • A goroutine starts with 2 KB stack size which can grow and shrink as needed. • Go prefers allocation on the stack. • Stack allocation is cheaper because it only requires two CPU instructions: one to push onto the stack for allocation, and another to release(pop) from the stack. • Unfortunately not all data can use memory allocated on the stack. Stack allocation requires that the lifetime and memory footprint of a variable can be determined at compile time. • If it can’t be determined, a dynamic allocation onto the heap occurs at runtime. • The Go compiler uses a process called escape analysis to fi nd objects whose lifetime is known at compile-time and allocates them on the stack rather than in garbage collected heap memory.
  • 13. wednesday.is Garbage Collector It is form of automatic memory management. The Garbage Collector attempts to reclaim memory which was allocated by program, but is no longer referenced. Go’s garbage collector is a non-generational concurrent, tri-color mark and sweep garbage collector. Go’s garbage collection works in two phases, the mark phase, and sweep phase. GC uses the tri-color algorithm to analyse the use of memory blocks. This algorithm fi rst marks objects that are still being referenced as “alive”, and in the next phase sweep frees the memory of objects that are not alive.
  • 14. wednesday.is You don’t have to collect your garbage, but you can reduce your garbage. Restructure your structs. Reduce the number of long living objects. Remove pointers within pointers. Avoid unnecessary string/byte array allocations.
  • 16. wednesday.is Why do we do restructure structs…? While reading data, a modern Computer’s CPU’s internal data registers can hold and process 64 bits. This is called the word size (It is usually 32 bits or 64 bits). When we don’t align our data to fi t word sizes, padding is added for properly aligning fi elds in memory so that next fi eld can start at an o ff set that’s multiple of a word size.
  • 17. Thanks for your time..! wednesday.is