SlideShare a Scribd company logo
www.cloudflare.com!
Understanding Go Memory
September 11, 2013
John Graham-Cumming
www.cloudflare.com!
Allocation Primitives
•  new(T)!
•  Allocates memory for item with type T!
•  Zeroes it

!
•  make(T)!
•  Allocates memory for item with type T!
•  Initializes it
•  Needed for channels, maps and slices
•  Memory comes from internal heap
ret = runtime·mallocgc(typ->size, flag, 1, 1);!
zeroed
www.cloudflare.com!
Two memory freeing processes 

•  Garbage collection
•  Determines which blocks of memory are no longer used
•  Marks areas of heap so they can be reused by your program

•  Scavenging
•  Determines when parts of the heap are idle for a long time
•  Returns memory to the operation system
www.cloudflare.com!
Garbage collection
•  Controlled by the GOGC environment variable
•  And by debug.SetGCPercentage()!
•  Default is same as GOGC=100!
•  Can set GOGC=off or debug.SetGCPercentage(-1) (no
garbage collection at all)
// Initialized from $GOGC. GOGC=off means no gc.!
//!
// Next gc is after we've allocated an extra amount of!
// memory proportional to the amount already in use.!
// If gcpercent=100 and we're using 4M, we'll gc again!
// when we get to 8M. This keeps the gc cost in linear!
// proportion to the allocation cost. Adjusting gcpercent!
// just changes the linear constant (and also the amount of!
// extra memory used).!
www.cloudflare.com!
Scavenging
•  Runs once per minute
•  Can also force return of all unused memory by calling
debug.FreeOSMemory()!
// If we go two minutes without a garbage collection, !
// force one to run.!
forcegc = 2*60*1e9;!
!
// If a span goes unused for 5 minutes after a garbage!
// collection, we hand it back to the operating system.!
limit = 5*60*1e9;!
www.cloudflare.com!
Memory Statistics
•  Read with runtime.ReadMemStats(&m)

!
•  The MemStats struct has tons of members
•  Useful ones for looking at heap
•  HeapInuse - # bytes in the heap allocated to things
•  HeapIdle - # bytes in heap waiting to be used
•  HeapSys - # bytes obtained from OS
•  HeapReleased - # bytes released to OS
www.cloudflare.com!
Test garbage making program
func makeBuffer() []byte { !
return make([]byte, rand.Intn(5000000)+5000000) !
}!
!
func main() { !
pool := make([][]byte, 20)!
!
makes := 0 !
for { !
b := makeBuffer()

makes += 1!
!
i := rand.Intn(len(pool))!
pool[i] = b!
!
time.Sleep(time.Second)!
}!
}!
www.cloudflare.com!
What happens
www.cloudflare.com!
debug.FreeOSMemory()!
www.cloudflare.com!
Use a buffered channel
func main() {!
pool := make([][]byte, 20)!
idle:= make(chan []byte, 5)!
!
makes := 0!
for {!
var b []byte!
select {!
case b = <-idle:!
default:!
makes += 1!
b = makeBuffer()!
}!
!
!
i := rand.Intn(len(pool))!
if pool[i] != nil {!
select {!
case idle<- pool[i]:!
pool[i] = nil!
default:!
}!
}!
!
pool[i] = b!
!
time.Sleep(time.Second)!
}!
}
www.cloudflare.com!
select for non-blocking receive
idle:= make(chan []byte, 5)!
!
select {!
case b = <-idle:

!
default:!
makes += 1!
b = makeBuffer()!
}!
Try to get from the
idle queue
Idle queue
empty? Make a
new buffer
A buffered
channel makes a
simple queue
www.cloudflare.com!
select for non-blocking send
idle:= make(chan []byte, 5)!
!
select {!
case buffer <- pool[i]:!
pool[i] = nil!
!
default:!
}!
A buffered
channel makes a
simple queue
Try to return buffer
to the idle queue
Idle queue full?
GC will have to
deal with the
buffer
www.cloudflare.com!
What happens
www.cloudflare.com!
More realistic: 20 goroutines
func main() {!
pool := make([][]byte, 200)!
!
for i := 0; i < 10; i++ {!
go func(offset int) {!
for {!
b := makeBuffer()!
j := offset+rand.Intn(20)!
pool[j] = b!
!
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))!
}!
}(i*20)!
}!
}!
www.cloudflare.com!
What happens
www.cloudflare.com!
Shared across goroutines
func main() {!
buffer := make(chan []byte, 5)!
!
pool := make([][]byte, 200)!
for i := 0; i < 10; i++ {!
go func(offset int) {!
for {!
var b []byte!
select {!
case b = <-buffer:!
default: b = makeBuffer()!
}!
j := offset+rand.Intn(20)!
if pool[j] != nil {!
select {!
case buffer <- pool[j]: pool[j] = nil!
default:!
}!
}!
pool[j] = b!
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))!
}!
}(i*20)!
}!
!
www.cloudflare.com!
What Happens
www.cloudflare.com!
More realistic example
•  Alter code to
•  Always try to give back a random buffer from the pool
•  50% of the time get a new one
•  Should create more garbage
www.cloudflare.com!
Idle length 5
www.cloudflare.com!
Idle length 20
www.cloudflare.com!
Idle length 50
www.cloudflare.com!
Also
•  This works for things other than []byte
•  Can be done with arbitrary types
•  Just need some way to reset
•  There’s a proposal to add something like this to the Go
package library
•  sync.Cache
•  Follow TODO

More Related Content

What's hot

Lua: the world's most infuriating language
Lua: the world's most infuriating languageLua: the world's most infuriating language
Lua: the world's most infuriating language
jgrahamc
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
Saša Tatar
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
Oliver N
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
siuyin
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to GoCloudflare
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go ConcurrencyCloudflare
 
Go Concurrency Basics
Go Concurrency Basics Go Concurrency Basics
Go Concurrency Basics
ElifTech
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
borderj
 
Event loop
Event loopEvent loop
Event loop
codepitbull
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
Anton Arhipov
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
Stefan
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
Maxym Kharchenko
 
Scaling FastAGI Applications with Go
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with Go
Digium
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
ElifTech
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
Lukasz Dobrzanski
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
Jung Kim
 
Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Media Gorod
 
GoLang & GoatCore
GoLang & GoatCore GoLang & GoatCore
GoLang & GoatCore
Sebastian Pożoga
 

What's hot (20)

Lua: the world's most infuriating language
Lua: the world's most infuriating languageLua: the world's most infuriating language
Lua: the world's most infuriating language
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Go Concurrency Basics
Go Concurrency Basics Go Concurrency Basics
Go Concurrency Basics
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Event loop
Event loopEvent loop
Event loop
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
 
Scaling FastAGI Applications with Go
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with Go
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 
Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Владимир Перепелица "Модули"
Владимир Перепелица "Модули"
 
GoLang & GoatCore
GoLang & GoatCore GoLang & GoatCore
GoLang & GoatCore
 

Similar to Go memory

[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe
SAP HANA Cloud Platform
 
OS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switchOS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switch
Daniel Ben-Zvi
 
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupДоклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Badoo Development
 
Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
Yoav Avrahami
 
Small Screen Development
Small Screen DevelopmentSmall Screen Development
Small Screen Development
Ralph von der Heyden
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
Aerospike
 
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek GrębskiJDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
PROIDEA
 
On heap cache vs off-heap cache
On heap cache vs off-heap cacheOn heap cache vs off-heap cache
On heap cache vs off-heap cache
rgrebski
 
GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.
Timothy Tsvetkov
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Víctor Bolinches
 
php & performance
 php & performance php & performance
php & performance
simon8410
 
Storm Anatomy
Storm AnatomyStorm Anatomy
Storm Anatomy
Eiichiro Uchiumi
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis
Moabi.com
 
Compromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging MechanismsCompromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging Mechanisms
Russell Sanford
 
Parallel Computing in R
Parallel Computing in RParallel Computing in R
Parallel Computing in R
mickey24
 
2015-GopherCon-Talk-Uptime.pdf
2015-GopherCon-Talk-Uptime.pdf2015-GopherCon-Talk-Uptime.pdf
2015-GopherCon-Talk-Uptime.pdf
UtabeUtabe
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
毅 吕
 

Similar to Go memory (20)

Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe
 
OS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switchOS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switch
 
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupДоклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
 
Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
 
Small Screen Development
Small Screen DevelopmentSmall Screen Development
Small Screen Development
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
 
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek GrębskiJDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
 
On heap cache vs off-heap cache
On heap cache vs off-heap cacheOn heap cache vs off-heap cache
On heap cache vs off-heap cache
 
GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
php & performance
 php & performance php & performance
php & performance
 
Objective-c memory
Objective-c memoryObjective-c memory
Objective-c memory
 
Storm Anatomy
Storm AnatomyStorm Anatomy
Storm Anatomy
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis
 
Compromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging MechanismsCompromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging Mechanisms
 
Parallel Computing in R
Parallel Computing in RParallel Computing in R
Parallel Computing in R
 
2015-GopherCon-Talk-Uptime.pdf
2015-GopherCon-Talk-Uptime.pdf2015-GopherCon-Talk-Uptime.pdf
2015-GopherCon-Talk-Uptime.pdf
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
 

More from jgrahamc

Better living through microcontrollers
Better living through microcontrollersBetter living through microcontrollers
Better living through microcontrollers
jgrahamc
 
Big O London Meetup April 2015
Big O London Meetup April 2015Big O London Meetup April 2015
Big O London Meetup April 2015
jgrahamc
 
How to launch and defend against a DDoS
How to launch and defend against a DDoSHow to launch and defend against a DDoS
How to launch and defend against a DDoSjgrahamc
 
Software Debugging for High-altitude Balloons
Software Debugging for High-altitude BalloonsSoftware Debugging for High-altitude Balloons
Software Debugging for High-altitude Balloons
jgrahamc
 
Highlights of Go 1.1
Highlights of Go 1.1Highlights of Go 1.1
Highlights of Go 1.1
jgrahamc
 
That'll never work!
That'll never work!That'll never work!
That'll never work!jgrahamc
 
Javascript Security
Javascript SecurityJavascript Security
Javascript Security
jgrahamc
 

More from jgrahamc (7)

Better living through microcontrollers
Better living through microcontrollersBetter living through microcontrollers
Better living through microcontrollers
 
Big O London Meetup April 2015
Big O London Meetup April 2015Big O London Meetup April 2015
Big O London Meetup April 2015
 
How to launch and defend against a DDoS
How to launch and defend against a DDoSHow to launch and defend against a DDoS
How to launch and defend against a DDoS
 
Software Debugging for High-altitude Balloons
Software Debugging for High-altitude BalloonsSoftware Debugging for High-altitude Balloons
Software Debugging for High-altitude Balloons
 
Highlights of Go 1.1
Highlights of Go 1.1Highlights of Go 1.1
Highlights of Go 1.1
 
That'll never work!
That'll never work!That'll never work!
That'll never work!
 
Javascript Security
Javascript SecurityJavascript Security
Javascript Security
 

Recently uploaded

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 

Recently uploaded (20)

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

Go memory

  • 2. www.cloudflare.com! Allocation Primitives •  new(T)! •  Allocates memory for item with type T! •  Zeroes it ! •  make(T)! •  Allocates memory for item with type T! •  Initializes it •  Needed for channels, maps and slices •  Memory comes from internal heap ret = runtime·mallocgc(typ->size, flag, 1, 1);! zeroed
  • 3. www.cloudflare.com! Two memory freeing processes •  Garbage collection •  Determines which blocks of memory are no longer used •  Marks areas of heap so they can be reused by your program •  Scavenging •  Determines when parts of the heap are idle for a long time •  Returns memory to the operation system
  • 4. www.cloudflare.com! Garbage collection •  Controlled by the GOGC environment variable •  And by debug.SetGCPercentage()! •  Default is same as GOGC=100! •  Can set GOGC=off or debug.SetGCPercentage(-1) (no garbage collection at all) // Initialized from $GOGC. GOGC=off means no gc.! //! // Next gc is after we've allocated an extra amount of! // memory proportional to the amount already in use.! // If gcpercent=100 and we're using 4M, we'll gc again! // when we get to 8M. This keeps the gc cost in linear! // proportion to the allocation cost. Adjusting gcpercent! // just changes the linear constant (and also the amount of! // extra memory used).!
  • 5. www.cloudflare.com! Scavenging •  Runs once per minute •  Can also force return of all unused memory by calling debug.FreeOSMemory()! // If we go two minutes without a garbage collection, ! // force one to run.! forcegc = 2*60*1e9;! ! // If a span goes unused for 5 minutes after a garbage! // collection, we hand it back to the operating system.! limit = 5*60*1e9;!
  • 6. www.cloudflare.com! Memory Statistics •  Read with runtime.ReadMemStats(&m)
 ! •  The MemStats struct has tons of members •  Useful ones for looking at heap •  HeapInuse - # bytes in the heap allocated to things •  HeapIdle - # bytes in heap waiting to be used •  HeapSys - # bytes obtained from OS •  HeapReleased - # bytes released to OS
  • 7. www.cloudflare.com! Test garbage making program func makeBuffer() []byte { ! return make([]byte, rand.Intn(5000000)+5000000) ! }! ! func main() { ! pool := make([][]byte, 20)! ! makes := 0 ! for { ! b := makeBuffer()
 makes += 1! ! i := rand.Intn(len(pool))! pool[i] = b! ! time.Sleep(time.Second)! }! }!
  • 10. www.cloudflare.com! Use a buffered channel func main() {! pool := make([][]byte, 20)! idle:= make(chan []byte, 5)! ! makes := 0! for {! var b []byte! select {! case b = <-idle:! default:! makes += 1! b = makeBuffer()! }! ! ! i := rand.Intn(len(pool))! if pool[i] != nil {! select {! case idle<- pool[i]:! pool[i] = nil! default:! }! }! ! pool[i] = b! ! time.Sleep(time.Second)! }! }
  • 11. www.cloudflare.com! select for non-blocking receive idle:= make(chan []byte, 5)! ! select {! case b = <-idle:
 ! default:! makes += 1! b = makeBuffer()! }! Try to get from the idle queue Idle queue empty? Make a new buffer A buffered channel makes a simple queue
  • 12. www.cloudflare.com! select for non-blocking send idle:= make(chan []byte, 5)! ! select {! case buffer <- pool[i]:! pool[i] = nil! ! default:! }! A buffered channel makes a simple queue Try to return buffer to the idle queue Idle queue full? GC will have to deal with the buffer
  • 14. www.cloudflare.com! More realistic: 20 goroutines func main() {! pool := make([][]byte, 200)! ! for i := 0; i < 10; i++ {! go func(offset int) {! for {! b := makeBuffer()! j := offset+rand.Intn(20)! pool[j] = b! ! time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))! }! }(i*20)! }! }!
  • 16. www.cloudflare.com! Shared across goroutines func main() {! buffer := make(chan []byte, 5)! ! pool := make([][]byte, 200)! for i := 0; i < 10; i++ {! go func(offset int) {! for {! var b []byte! select {! case b = <-buffer:! default: b = makeBuffer()! }! j := offset+rand.Intn(20)! if pool[j] != nil {! select {! case buffer <- pool[j]: pool[j] = nil! default:! }! }! pool[j] = b! time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))! }! }(i*20)! }! !
  • 18. www.cloudflare.com! More realistic example •  Alter code to •  Always try to give back a random buffer from the pool •  50% of the time get a new one •  Should create more garbage
  • 22. www.cloudflare.com! Also •  This works for things other than []byte •  Can be done with arbitrary types •  Just need some way to reset •  There’s a proposal to add something like this to the Go package library •  sync.Cache •  Follow TODO