SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
Cloudflare
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
Cloudflare
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
seanmcq
 
Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Владимир Перепелица "Модули"
Владимир Перепелица "Модули"
Media Gorod
 
GoLang & GoatCore
GoLang & GoatCore GoLang & GoatCore
GoLang & GoatCore
Sebastian Pożoga
 

Mais procurados (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
 

Semelhante a Go memory

JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 

Semelhante a 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
 

Mais de 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
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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