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

PDF
Go Profiling - John Graham-Cumming
PDF
Go Memory
PDF
Go debugging and troubleshooting tips - from real life lessons at SignalFx
PDF
Go Containers
PDF
Go Concurrency
PPTX
HAB Software Woes
PDF
Golang Channels
PDF
Goroutines and Channels in practice
Go Profiling - John Graham-Cumming
Go Memory
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go Containers
Go Concurrency
HAB Software Woes
Golang Channels
Goroutines and Channels in practice

What's hot (20)

PPTX
Lua: the world's most infuriating language
PPTX
All you need to know about the JavaScript event loop
PDF
Concurrency in Golang
PDF
Go concurrency
PDF
An Introduction to Go
PDF
Go Concurrency
PPTX
Go Concurrency Basics
PPT
Concurrency in go
PDF
Event loop
PDF
Something about Golang
PDF
A CTF Hackers Toolbox
PPTX
2015 555 kharchenko_ppt
PDF
Scaling FastAGI Applications with Go
KEY
Gevent what's the point
PPTX
Go Concurrency Patterns
PDF
Python Async IO Horizon
PDF
Coroutines for Kotlin Multiplatform in Practise
PDF
Letswift19-clean-architecture
ODP
Владимир Перепелица "Модули"
PDF
GoLang & GoatCore
Lua: the world's most infuriating language
All you need to know about the JavaScript event loop
Concurrency in Golang
Go concurrency
An Introduction to Go
Go Concurrency
Go Concurrency Basics
Concurrency in go
Event loop
Something about Golang
A CTF Hackers Toolbox
2015 555 kharchenko_ppt
Scaling FastAGI Applications with Go
Gevent what's the point
Go Concurrency Patterns
Python Async IO Horizon
Coroutines for Kotlin Multiplatform in Practise
Letswift19-clean-architecture
Владимир Перепелица "Модули"
GoLang & GoatCore
Ad

Similar to Go memory (20)

PDF
[BGOUG] Java GC - Friend or Foe
PDF
OS scheduling and The anatomy of a context switch
PDF
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
PPTX
Jvm memory model
KEY
Small Screen Development
PDF
Golang Performance : microbenchmarks, profilers, and a war story
PDF
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
PDF
On heap cache vs off-heap cache
PDF
GC in Ruby. RubyC, Kiev, 2014.
PDF
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
PDF
php & performance
PDF
Objective-c memory
PDF
Storm Anatomy
KEY
JavaOne 2012 - JVM JIT for Dummies
PPT
[CCC-28c3] Post Memory Corruption Memory Analysis
PDF
Compromising Linux Virtual Machines with Debugging Mechanisms
KEY
Parallel Computing in R
PPTX
A Deterministic Walk Down TigerBeetle’s main() Street
PDF
2015-GopherCon-Talk-Uptime.pdf
[BGOUG] Java GC - Friend or Foe
OS scheduling and The anatomy of a context switch
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Jvm memory model
Small Screen Development
Golang Performance : microbenchmarks, profilers, and a war story
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
On heap cache vs off-heap cache
GC in Ruby. RubyC, Kiev, 2014.
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
php & performance
Objective-c memory
Storm Anatomy
JavaOne 2012 - JVM JIT for Dummies
[CCC-28c3] Post Memory Corruption Memory Analysis
Compromising Linux Virtual Machines with Debugging Mechanisms
Parallel Computing in R
A Deterministic Walk Down TigerBeetle’s main() Street
2015-GopherCon-Talk-Uptime.pdf
Ad

More from jgrahamc (7)

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

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
DOCX
The AUB Centre for AI in Media Proposal.docx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Digital-Transformation-Roadmap-for-Companies.pptx
Chapter 3 Spatial Domain Image Processing.pdf
cuic standard and advanced reporting.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Weekly Chronicles - August'25 Week I
sap open course for s4hana steps from ECC to s4
Programs and apps: productivity, graphics, security and other tools
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Reach Out and Touch Someone: Haptics and Empathic Computing
Spectral efficient network and resource selection model in 5G networks
Advanced methodologies resolving dimensionality complications for autism neur...
The AUB Centre for AI in Media Proposal.docx

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