SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
Ruby Memory
Tips and Tricks
Hi, I’m Bruce
6 ½ years experience developing
complex Ruby on Rails applications
4 years as Senior Lead Developer
at Prezentt
5 years as Technical Director at
GTP iCommerce
Agenda
• Introduction to the Garbage Collector
• Garbage Collector Tuning
• General tips and tricks
C code vs Ruby cde
void my_function() {
char *stack = "Hello";
char *heap = malloc(6);
strncopy(heap, "world", 5);
free(heap);
}
Memory explicitly allocated on the
stack or the heap
Heap allocated memory must be
free()’d or it will leak
def my_function
local = "Hello"
@instance = "world"
end
No stack allocated variables, even local
variables live on the heap
Memory is freed automatically
How does it do this?
Garbage Collection
The Ruby interpreter will trigger
garbage collection to free memory
when certain conditions are met.
Ruby uses a “Stop the world”
mechanism which is the cause of
many performance problems.
How Garbage Collection Works
Ruby < 2.0 used various mark and sweep algorithms.
Traverses object graph and checks if the memory is still in
use.
Ruby 2.0 replaced it with a Bitmap Marking algorithm. Each
heap has a corresponding memory structure with bit
values indicating if allocated memory is still in use.
Ruby 2.1 added a Generational Garbage Collection
algorithm. “Minor” sweep focuses on newly allocated
memory. “Major” sweep checks entire object graph.
Garbage Collection Triggers
Minor Garbage Collection (Fast, looks at new objects)
• Not enough space on the heap to allocate new objects
• Every 16-32Mb of memory allocated in new objects
Major Garbage Collection (Slow, looks at all objects)
• Number of old objects increases by more than a factor of 2
• Every 16-32Mb of memory allocated in old objects
Garbage Collection Tuning
Goal is to manage a tradeoff between memory usage vs. the
frequency and duration of garbage collection.
RUBY_GC_HEAP_GROWTH_FACTOR (1.8)
The factor by which the size of the heap grows when it needs to be expanded
RUBY_GC_MALLOC_LIMIT & _MAX (16Mb - 32Mb)
The minimum value for malloc limits that would trigger a Minor Garbage
Collection.
RUBY_GC_OLDMALLOC_LIMIT & _MAX (16Mb - 32Mb)
The minimum value for malloc limits that would trigger a Major Garbage
Collection.
Garbage Collection Tuning (Cont)
How do we know which values to change, and to what?
• Monitor changes with GC.stat
• Great third party tools like New Relic and Scout
• My favourite: TuneMyGC (https://tunemygc.com/)
TuneMyGC
How do we know which values t change, and to what?
• Monitor changes with GC.stat
• Great third party tools like New Relic and Scout
• My favourite: TuneMyGC (https://tunemygc.com/)
TuneMyGC
TuneMyGC
TuneMyGC
Ruby Memory Tools
allocation_tracer gem
memory_profiler gem
Third party tools like New Relic and Scout
Memory Efficient Ruby
Lots of advice out there on micro-optimisation, avoid:
require 'objspace'
ObjectSpace.memsize_of([]) # => 40
ObjectSpace.memsize_of([1,2,3]) # => 40
ObjectSpace.memsize_of([1,2,3,4]) # => 72
Writing beautiful Ruby is more important than saving mere
bytes.
The best memory saving comes from not allocating
additional objects if you can avoid it.
Memory Efficient Ruby
require 'memory_profiler'
large_array = [*1..1_000_000]
report = MemoryProfiler.report do
new_array = large_array.map { |el| el * 2 }
end
report.total_allocated_memsize # => 8000040
report = MemoryProfiler.report do
large_array.map! { |el| el * 2 }
end
report.total_allocated_memsize # => 0
Memory Efficient Ruby
require 'memory_profiler'
string_1 = "Hello"
string_2 = "world"
string_1.object_id # => 47213217995200
report = MemoryProfiler.report do
string_1 << string_2
end
report.total_allocated_memsize # => 0
string_1.object_id # => 47213217995200
report = MemoryProfiler.report do
string_1 += string_2
end
report.total_allocated_memsize # => 40
string_1.object_id # => 47213218585840
Memory Efficient Ruby
# I want to turn [1, 2, 3] into {1 => 1, 2 => 2, 3 => 3}
require 'memory_profiler'
require 'benchmark'
large_array = [*1..15_000]
def merge!(array)
array.inject({}) { |k, v| k.merge!(v => v) }
end
def merge(array)
array.inject({}) { |k, v| k.merge(v => v) }
end
report = MemoryProfiler.report do
merge(large_array)
end
report.total_allocated_memsize # => 4_380_180_392
report = MemoryProfiler.report do
merge!(large_array)
end
report.total_allocated_memsize # => 3_338_848
Memory Efficient Ruby
# I want to turn [1, 2, 3] into {1 => 1, 2 => 2, 3 => 3}
require 'memory_profiler'
require 'benchmark'
large_array = [*1..15_000]
def merge!(array)
array.inject({}) { |k, v| k.merge!(v => v) }
end
def merge(array)
array.inject({}) { |k, v| k.merge(v => v) }
end
Benchmark.bm(10) do |b|
b.report("merge") { merge(large_array) }
b.report("merge!") { merge!(large_array) }
end
# user system total real
# merge 7.390000 0.080000 7.470000 ( 7.475560)
# merge! 0.010000 0.000000 0.010000 ( 0.008071)
Thanks!
Can be reached at:
bruce@werdschinski.com
@bwerdschinski
http://www.werdschinski.com

Mais conteúdo relacionado

Mais procurados

HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?bzamecnik
 
.Net Garbage Collector 101
.Net Garbage Collector 101.Net Garbage Collector 101
.Net Garbage Collector 101Woody Pewitt
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodbLee Theobald
 
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Data Con LA
 
Do something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as databaseDo something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as databaseBruce McPherson
 
PHPConPl 2013 - Allowed memory size of X bytes exhausted
PHPConPl 2013 - Allowed memory size of X bytes exhaustedPHPConPl 2013 - Allowed memory size of X bytes exhausted
PHPConPl 2013 - Allowed memory size of X bytes exhaustedPiotr Pasich
 
Probabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityProbabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityAndrii Gakhov
 
Do something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a databaseDo something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a databaseBruce McPherson
 
Do something in 5 with gas 7-email log
Do something in 5 with gas 7-email logDo something in 5 with gas 7-email log
Do something in 5 with gas 7-email logBruce McPherson
 
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheetDo something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheetBruce McPherson
 
In class, we discussed min-heaps. In a min-heap the element of the heap with ...
In class, we discussed min-heaps. In a min-heap the element of the heap with ...In class, we discussed min-heaps. In a min-heap the element of the heap with ...
In class, we discussed min-heaps. In a min-heap the element of the heap with ...licservernoida
 
October 2013 BARUG Lightning Talk
October 2013 BARUG Lightning TalkOctober 2013 BARUG Lightning Talk
October 2013 BARUG Lightning TalkClark Fitzgerald
 
Do something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing appDo something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing appBruce McPherson
 
Climate data in r with the raster package
Climate data in r with the raster packageClimate data in r with the raster package
Climate data in r with the raster packageAlberto Labarga
 
Профилирование и оптимизация производительности Ruby-кода
Профилирование и оптимизация производительности Ruby-кодаПрофилирование и оптимизация производительности Ruby-кода
Профилирование и оптимизация производительности Ruby-кодаsamsolutionsby
 
GEO mapbox geo_api_develop2 Intro
 GEO mapbox geo_api_develop2 Intro GEO mapbox geo_api_develop2 Intro
GEO mapbox geo_api_develop2 IntroMax Kleiner
 
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Bruce McPherson
 
Event Loop in Javascript
Event Loop in JavascriptEvent Loop in Javascript
Event Loop in JavascriptDiptiGandhi4
 
Intro to Apache Spark - Lab
Intro to Apache Spark - LabIntro to Apache Spark - Lab
Intro to Apache Spark - LabMammoth Data
 
RxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowRxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowViliam Elischer
 

Mais procurados (20)

HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?
 
.Net Garbage Collector 101
.Net Garbage Collector 101.Net Garbage Collector 101
.Net Garbage Collector 101
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodb
 
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
 
Do something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as databaseDo something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as database
 
PHPConPl 2013 - Allowed memory size of X bytes exhausted
PHPConPl 2013 - Allowed memory size of X bytes exhaustedPHPConPl 2013 - Allowed memory size of X bytes exhausted
PHPConPl 2013 - Allowed memory size of X bytes exhausted
 
Probabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityProbabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. Cardinality
 
Do something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a databaseDo something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a database
 
Do something in 5 with gas 7-email log
Do something in 5 with gas 7-email logDo something in 5 with gas 7-email log
Do something in 5 with gas 7-email log
 
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheetDo something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
 
In class, we discussed min-heaps. In a min-heap the element of the heap with ...
In class, we discussed min-heaps. In a min-heap the element of the heap with ...In class, we discussed min-heaps. In a min-heap the element of the heap with ...
In class, we discussed min-heaps. In a min-heap the element of the heap with ...
 
October 2013 BARUG Lightning Talk
October 2013 BARUG Lightning TalkOctober 2013 BARUG Lightning Talk
October 2013 BARUG Lightning Talk
 
Do something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing appDo something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing app
 
Climate data in r with the raster package
Climate data in r with the raster packageClimate data in r with the raster package
Climate data in r with the raster package
 
Профилирование и оптимизация производительности Ruby-кода
Профилирование и оптимизация производительности Ruby-кодаПрофилирование и оптимизация производительности Ruby-кода
Профилирование и оптимизация производительности Ruby-кода
 
GEO mapbox geo_api_develop2 Intro
 GEO mapbox geo_api_develop2 Intro GEO mapbox geo_api_develop2 Intro
GEO mapbox geo_api_develop2 Intro
 
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
 
Event Loop in Javascript
Event Loop in JavascriptEvent Loop in Javascript
Event Loop in Javascript
 
Intro to Apache Spark - Lab
Intro to Apache Spark - LabIntro to Apache Spark - Lab
Intro to Apache Spark - Lab
 
RxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowRxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrow
 

Semelhante a Ruby memory tips and tricks

Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...
Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...
Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...Alexander Dymo
 
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
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection TechniquesAn Khuong
 
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"LogeekNightUkraine
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4aminmesbahi
 
Rails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume LuccisanoRails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume LuccisanoGuillaume Luccisano
 
Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMjaganmohanreddyk
 
Use Ruby GC in full..
Use Ruby GC in full..Use Ruby GC in full..
Use Ruby GC in full..Alex Mercer
 
Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey J On The Beach
 
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Anna Shymchenko
 
FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...
FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...
FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...Rob Skillington
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionSomya Bagai
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Maarten Balliauw
 
Sharding in MongoDB 4.2 #what_is_new
 Sharding in MongoDB 4.2 #what_is_new Sharding in MongoDB 4.2 #what_is_new
Sharding in MongoDB 4.2 #what_is_newAntonios Giannopoulos
 
this-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxthis-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxTier1 app
 
dotMemory 4 - What's inside?
dotMemory 4 - What's inside?dotMemory 4 - What's inside?
dotMemory 4 - What's inside?Maarten Balliauw
 

Semelhante a Ruby memory tips and tricks (20)

Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...
Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...
Alexander Dymo - RailsConf 2014 - Improve performance: Optimize Memory and Up...
 
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
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection Techniques
 
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4
 
Rails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume LuccisanoRails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume Luccisano
 
Garbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVMGarbage Collection in Hotspot JVM
Garbage Collection in Hotspot JVM
 
Use Ruby GC in full..
Use Ruby GC in full..Use Ruby GC in full..
Use Ruby GC in full..
 
Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey
 
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...
FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...
FOSDEM 2019: M3, Prometheus and Graphite with metrics and monitoring in an in...
 
GC in C#
GC in C#GC in C#
GC in C#
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
 
Sharding in MongoDB 4.2 #what_is_new
 Sharding in MongoDB 4.2 #what_is_new Sharding in MongoDB 4.2 #what_is_new
Sharding in MongoDB 4.2 #what_is_new
 
this-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxthis-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptx
 
Rails Performance
Rails PerformanceRails Performance
Rails Performance
 
dotMemory 4 - What's inside?
dotMemory 4 - What's inside?dotMemory 4 - What's inside?
dotMemory 4 - What's inside?
 

Último

Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 

Último (20)

Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 

Ruby memory tips and tricks

  • 2. Hi, I’m Bruce 6 ½ years experience developing complex Ruby on Rails applications 4 years as Senior Lead Developer at Prezentt 5 years as Technical Director at GTP iCommerce
  • 3. Agenda • Introduction to the Garbage Collector • Garbage Collector Tuning • General tips and tricks
  • 4. C code vs Ruby cde void my_function() { char *stack = "Hello"; char *heap = malloc(6); strncopy(heap, "world", 5); free(heap); } Memory explicitly allocated on the stack or the heap Heap allocated memory must be free()’d or it will leak def my_function local = "Hello" @instance = "world" end No stack allocated variables, even local variables live on the heap Memory is freed automatically How does it do this?
  • 5. Garbage Collection The Ruby interpreter will trigger garbage collection to free memory when certain conditions are met. Ruby uses a “Stop the world” mechanism which is the cause of many performance problems.
  • 6. How Garbage Collection Works Ruby < 2.0 used various mark and sweep algorithms. Traverses object graph and checks if the memory is still in use. Ruby 2.0 replaced it with a Bitmap Marking algorithm. Each heap has a corresponding memory structure with bit values indicating if allocated memory is still in use. Ruby 2.1 added a Generational Garbage Collection algorithm. “Minor” sweep focuses on newly allocated memory. “Major” sweep checks entire object graph.
  • 7. Garbage Collection Triggers Minor Garbage Collection (Fast, looks at new objects) • Not enough space on the heap to allocate new objects • Every 16-32Mb of memory allocated in new objects Major Garbage Collection (Slow, looks at all objects) • Number of old objects increases by more than a factor of 2 • Every 16-32Mb of memory allocated in old objects
  • 8. Garbage Collection Tuning Goal is to manage a tradeoff between memory usage vs. the frequency and duration of garbage collection. RUBY_GC_HEAP_GROWTH_FACTOR (1.8) The factor by which the size of the heap grows when it needs to be expanded RUBY_GC_MALLOC_LIMIT & _MAX (16Mb - 32Mb) The minimum value for malloc limits that would trigger a Minor Garbage Collection. RUBY_GC_OLDMALLOC_LIMIT & _MAX (16Mb - 32Mb) The minimum value for malloc limits that would trigger a Major Garbage Collection.
  • 9. Garbage Collection Tuning (Cont) How do we know which values to change, and to what? • Monitor changes with GC.stat • Great third party tools like New Relic and Scout • My favourite: TuneMyGC (https://tunemygc.com/)
  • 10. TuneMyGC How do we know which values t change, and to what? • Monitor changes with GC.stat • Great third party tools like New Relic and Scout • My favourite: TuneMyGC (https://tunemygc.com/)
  • 14. Ruby Memory Tools allocation_tracer gem memory_profiler gem Third party tools like New Relic and Scout
  • 15. Memory Efficient Ruby Lots of advice out there on micro-optimisation, avoid: require 'objspace' ObjectSpace.memsize_of([]) # => 40 ObjectSpace.memsize_of([1,2,3]) # => 40 ObjectSpace.memsize_of([1,2,3,4]) # => 72 Writing beautiful Ruby is more important than saving mere bytes. The best memory saving comes from not allocating additional objects if you can avoid it.
  • 16. Memory Efficient Ruby require 'memory_profiler' large_array = [*1..1_000_000] report = MemoryProfiler.report do new_array = large_array.map { |el| el * 2 } end report.total_allocated_memsize # => 8000040 report = MemoryProfiler.report do large_array.map! { |el| el * 2 } end report.total_allocated_memsize # => 0
  • 17. Memory Efficient Ruby require 'memory_profiler' string_1 = "Hello" string_2 = "world" string_1.object_id # => 47213217995200 report = MemoryProfiler.report do string_1 << string_2 end report.total_allocated_memsize # => 0 string_1.object_id # => 47213217995200 report = MemoryProfiler.report do string_1 += string_2 end report.total_allocated_memsize # => 40 string_1.object_id # => 47213218585840
  • 18. Memory Efficient Ruby # I want to turn [1, 2, 3] into {1 => 1, 2 => 2, 3 => 3} require 'memory_profiler' require 'benchmark' large_array = [*1..15_000] def merge!(array) array.inject({}) { |k, v| k.merge!(v => v) } end def merge(array) array.inject({}) { |k, v| k.merge(v => v) } end report = MemoryProfiler.report do merge(large_array) end report.total_allocated_memsize # => 4_380_180_392 report = MemoryProfiler.report do merge!(large_array) end report.total_allocated_memsize # => 3_338_848
  • 19. Memory Efficient Ruby # I want to turn [1, 2, 3] into {1 => 1, 2 => 2, 3 => 3} require 'memory_profiler' require 'benchmark' large_array = [*1..15_000] def merge!(array) array.inject({}) { |k, v| k.merge!(v => v) } end def merge(array) array.inject({}) { |k, v| k.merge(v => v) } end Benchmark.bm(10) do |b| b.report("merge") { merge(large_array) } b.report("merge!") { merge!(large_array) } end # user system total real # merge 7.390000 0.080000 7.470000 ( 7.475560) # merge! 0.010000 0.000000 0.010000 ( 0.008071)
  • 20. Thanks! Can be reached at: bruce@werdschinski.com @bwerdschinski http://www.werdschinski.com