Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Garbage Collection em Ruby
Search
Lauro Caetano
May 17, 2014
Programming
150
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Garbage Collection em Ruby
Palestra do TDC Florianópolis 2014
Lauro Caetano
May 17, 2014
Transcript
114 slides
Garbage Collection Ruby
Gerenciamento manual de memória
Objeto 01 Objeto 02
Desalocar manualmente
Objeto 01 Objeto 02
Objeto 01
Mas imagine o seguinte cenário
Objeto 01 Objeto 02
Objeto 01 Objeto 02
Referência para um objeto que não existe mais
Seu sistema pode quebrar
Ou pior…
Ele pode gerar resultados incorretos
Outras preocupações além do domínio da aplicação
Entender como os módulos que você utiliza gerenciam sua memória
Lauro Caetano @laurocaetano
None
None
Open Source
None
None
None
Rails
Rails core team
O que é Garbage Collection e como ele foi evoluindo
a cada nova versão do Ruby
Agenda • O que é Garbage Collection • Garbage Collection
no Ruby - Mark and sweep • Desvantagens do Mark and Sweep • Evolução • Lazy Sweep - Ruby 1.9 • Bitmap Mark - Ruby 2.0 • Generational Garbage Collection - Ruby 2.1
O que é Garbage Collection?
Gerenciamento dinâmico automático de memória
3 Responsabilidades
1. Alocar espaço para novos objetos
2. Identificar os objetos ainda vivos
3. Recuperar o espaço ocupado por objetos mortos
Garbage Collection no Ruby
Ruby ainda utiliza o mesmo algoritmo que foi inventado a
mais de 50 anos por John MacCarthy
Mark-Sweep
Free List
None
None
None
None
None
Hora de limpar o Heap
Stop the world
Percorre todos os objetos do heap e marca os que
ainda estão vivos
None
None
None
None
None
Varre novamente o heap, mas agora em busca dos objetos
não marcados e os remove do heap
None
None
None
None
None
None
None
None
Volta a executar o seu programa
Vamos ao código
! 1 def new! 2 ref = allocate! 3 !
4 if ref.nil?! 5 collect! 6 ! 7 if ref.nil?! 8 raise "Out of memory"! 9 end! 10 end! 11 end! ! !
12 ! 13 def collect! 14 mark_from_roots! 15 sweep(@heap_start, @heap_end)!
16 end! 17 ! ! !
17 ! 18 def mark_from_roots! 19 initialize(worklist)! 20 ! 21
@roots.each do |fld|! 22 ref = fld! 23 if !ref.nil? && !marked?(ref)! 24 set_marked(ref)! 25 mark! 26 end! 27 end! 28 end! 29
32 ! 33 def mark! 34 while(@worklist.any?)! 35 ref =
remove(worklist)! 36 ! 37 pointers(ref).each do |fld|! 38 child = fld! 39 ! 40 if !child.nil? && !marked?(child)! 41 set_marked(child)! 42 add(@worklist, child)! 43 end! 44 end! 45 end! 46 end! 47
47 ! 48 def sweep(heap_start, heap_end)! 49 scan = start!
50 ! 51 while (scan < heap_end)! 52 if marked?(scan)! 53 unset_marked(scan)! 54 else! 55 free(scan)! 56 end! 57 ! 58 scan = next_object(scan)! 59 end! 60 end
Desvantagens do Mark and sweep
Fazer Full GC toda hora que o heap está cheio
não parece uma boa ideia
Stop the world
Mark and sweep é proporcional ao tamanho do heap
Evolução
Lazy Sweep Ruby 1.9
Fazer Full GC toda hora que o heap está cheio
não parece uma boa ideia
Recuperar apenas o espaço necessário para criar um novo objeto
e permitir que a aplicação continue rodando
Agora o sweep não para mais o mundo todo
A alocação é responsável por checar se existe espaço disponível
Caso não tenha espaço disponível, fazer Lazy Sweep até obter
o espaço necessário
12 ! 13 def allocate(size)! 14 result = remove(size)! 15
! 16 if result.nil?! 17 lazy_sweep(size)! 18 result = remove(size)! 19 end! 20 ! 21 result! 22 end! 23
Bitmap Mark Ruby 2.0
None
Como os bits de marcação no ficavam objeto, os valores
eram sempre diferentes
Para possibilitar que o Unix compartilhe valores iguais
Os bits de marcação foram movidos para uma tabela de
bitmap
1 1 1 1 1 0 0
Generational Garbage Collection Ruby 2.1
Mark and sweep é proporcional ao tamanho do heap
Weak generational hypothesis
O coletor processa mais frequentemente objetos novos do que objetos
maduros
Um objeto maduro é aquele que permanece ativo por um
algum período de tempo
Enquanto um objeto novo é aquele que seu sistema acabou
de criar
Geração Nova Geração Madura
Quando o mark and sweep terminar, os objetos restantes serão
considerados maduros
Geração Nova Geração Madura
Geração Nova Geração Madura
Objetos maduros não serão marcados novamente até um próximo full
GC
Quando o full GC ocorrer, todos os objetos passarão pelo
mark and sweep
É legal entender como as coisas funcionam
Obrigado @laurocaetano github.com/laurocaetano
Bonus
JRuby and Rubinius.
Copying Garbage Collection
Segmento de memória contínua
Bump Allocation
Aloca segmentos adjacentes de memória, mantendo um ponteiro para a
próxima alocação
Próxima alocação
Próxima alocação
Próxima alocação
Objetos podem ser de tamanhos diferentes
A grande vantagem é que valores relacionados ficam próximos
A CPU pode cachear a região de memória que for
acessada frequentemente
Também utiliza o Garbage Collection Generacional
Ruby 2.2
GC Simbolos
https://bugs.ruby-lang.org/issues/9634
Obrigado @laurocaetano github.com/laurocaetano
More Decks by Lauro Caetano
See All by Lauro Caetano
Learning Elixir by Examples
laurocaetano
1
250
What's new in Rails 4.1
laurocaetano
0
110
Clojure Introduction.
laurocaetano
1
90
Other Decks in Programming
See All in Programming
FactoryBotをやめればRSpecは速くなるのか?
yuta_onishi_97
0
1.7k
社内AIエージェント「Askワンバン」における コストチューニングの取り組み
t0yohei
0
170
flutter_test のその先へ — Flutter アプリの LLM 機能に「評価」という品質保証を
kosukesaigusa
0
200
ActionController meets Protocol Buffers
sorah
1
800
作って学ぶSpring BootのAuto Configuration / JJUG Night Seminar 2026-10-19
rshindo
0
230
Getting Started with Vibe Coding
miccheng
0
210
Будущее локальных LLM – Алексей Голобурдин, PythoNN
sobolevn
0
120
Apple Intelligenceとオンデバイス時代の到来
yahir0
0
240
Spec-Driven Development - Why Vaadin Is the Perfect Fit
simas
PRO
0
240
React Native에 현대적인 빌드 도구 더하기: Rollipop 구현기
leegeunhyeok
0
180
AIで開発が速くなった先で、開発チームは何を目指すか
shihochan
1
2k
作れるエンジニアから、価値を届けるエンジニアへ
ryunakayama
1
260
Featured
See All Featured
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
6
920
Side Projects
sachag
456
43k
Highjacked: Video Game Concept Design
rkendrick25
PRO
2
560
Building a Modern Day E-commerce SEO Strategy
aleyda
45
9.3k
Agile Leadership in an Agile Organization
kimpetersen
PRO
0
310
JAMstack: Web Apps at Ludicrous Speed - All Things Open 2022
reverentgeek
1
680
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
4
4.4k
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.8k
The AI Search Optimization Roadmap by Aleyda Solis
aleyda
2
6.4k
職位にかかわらず全員がリーダーシップを発揮するチーム作り / Building a team where everyone can demonstrate leadership regardless of position
madoxten
70
69k
What Being in a Rock Band Can Teach Us About Real World SEO
427marketing
0
1.1k
Navigating Weather and Climate Data
rabernat
0
590