SlideShare a Scribd company logo
Globalcode – Open4education
Trilha – Ruby
Guilherme Baptista
Globalcode – Open4education
10 anos deixando linhas de
código por aí em lugares como:
Globalcode – Open4education
Stack Level too Deep
Tail Call Optimization
É uma boa ideia fazer recursão em Ruby?
Familiar
?
file.rb:10:in `call':
stack level too deep
(SystemStackError)
from file.rb:10:in `<main>'
Qual o
significado?file.rb:10:in `call':
stack level too deep
(SystemStackError)
from file.rb:10:in `<main>'
Qual o
significado?file.rb:10:in `call':
stack level too deep
(SystemStackError)
from file.rb:10:in `<main>'
stack
overflow?
file.rb:10:in `call':
stack level too deep
(SystemStackError)
from file.rb:10:in `<main>'
stack
overflow?
?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
file.rb:10:in `call':
stack level too deep
(SystemStackError)
from file.rb:10:in `<main>'
O que
é?
É uma “proteção”
contra loops
infinitos?
É uma “proteção”
contra loops
infinitos?
É uma “proteção”
contra loops
infinitos?
É uma “proteção”
contra loops
infinitos?
É uma “proteção”
contra loops
infinitos?
É um erro causado
por uso de
memória em
excesso?
É um erro causado por
uso de memória em
excesso?
É um erro causado por
uso de memória em
excesso?
É um erro causado por
uso de memória em
excesso?
file.rb:8:in `<main>':
failed to allocate memory
(NoMemoryError)
Bônus: Uma linha
para acabar com a
memória RAM em
segundos:
Obs.: Não rodar no irb do seu servidor em produção...
#fikdik
É uma “proteção”
para não deixar um
método chamar a si
mesmo?
É uma “proteção”
para não deixar um
método chamar a si
mesmo?
É uma “proteção”
para não deixar um
método chamar a si
mesmo?
Done
!
É uma “proteção” para
não deixar um método
chamar a si mesmo
muitas vezes?
É uma “proteção” para
não deixar um método
chamar a si mesmo
muitas vezes?
É uma “proteção” para
não deixar um método
chamar a si mesmo
muitas vezes?
Done
!
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
É uma “proteção” para não
deixar um método chamar
a si mesmo
infinitamente?
É uma “proteção” para não deixar um
método chamar a si mesmo
infinitamente?
file.rb:2:in `me_myself_and_i':
stack level too deep
(SystemStackError)
from file.rb:2:in
`me_myself_and_i'
from file.rb:2:in
`me_myself_and_i'
from file.rb:2:in
`me_myself_and_i'
from file.rb:2:in
`me_myself_and_i'
... 11901 levels...
from file.rb:2:in
Será?
5
1 + 1 + 1 + 1
+ 1
5
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
2000
0
2000
0
file.rb:7:in `eval':
stack level too deep
(SystemStackError)
from file.rb:7:in `<main>'
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
É uma “proteção” para não deixar um
método chamar a si mesmo
infinitamente?
file.rb:7:in `eval':
stack level too deep
(SystemStackError)
from file.rb:7:in `<main>'
Pode não ser bem isso...
Vamos falar sobre pilha:
Stack
(abstract data type)
LIFO: last-in, first-out
(o último que entra é o primeiro que sai)
Stack (LIFO: last-in, first-out)
Stac
k
Stack (LIFO: last-in, first-out)
Stack (LIFO: last-in, first-out)
Stack (LIFO: last-in, first-out)
Stack (LIFO: last-in, first-out)
Stack (LIFO: last-in, first-out)
Stack (LIFO: last-in, first-out)
Stack (LIFO: last-in, first-out)
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
Em Ruby tudo é objeto.
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
RubyVM::InstructionSequence
RubyVM::InstructionSequence.of
Proc
Ou
method
Ruby Code
down to
VM Instructions
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
YARBx02x00x00x00x03x00x00x00rx02x00x00x00x00x00x00x01x00
x00x00x02x00x00x00x04x00x00x00xF9x01x00x00xFDx01x00x00bx
02x00x00x86_64-
linuxx00*x00x00x00x00x00x00x00bx00x00x00x00x00x00x00*x00
x00x00x00x00x00x00x01x00x00x00x00x00x00x00Zx00x00x00x00x
00x00x00Zx00x00x00x00x00x00x00;x00x00x00x00x00x00x00x00x
00x00x00x00x00x00x00x00x00x00x00x00x00x00x00Zx00x00x00x0
0x00x00x00;x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00
x00x00x00x00x00x00x00x00Zx00x00x00x00x00x00x00;x00x00x00
x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x
00x00*x00x00x00x00x00x00x00x10x00x00x00x00x00x00x001x00x
00x00x00x00x00x00x00x00x00x00vx00x00x00x02x00x00x00rx00
x00x00x11x00x00x00x0Fx00x00x00x13x00x00x00rx00x00x00x01
x00x00x00x00x00x00x00x10x00x00x00x01x00x00x00x01x00x00x
00x00x00x00x00x10x00x00x00x01x00x00x00x01x00x00x00x00x00
x00x00x10x00x00x00x01x00x00x00x01x00x00x00x02x00x00x00x
01x00x00x00x14x00x00x009x00x00x00x00x00x00x00x00x00x00x0
0x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00
x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x0
0x00x00x00x00x00x00x00x01x00x00x00x00x00x00x00x01x00x00
x00x00x00x00x00x02x00x00x00x00x00x00x00x02x00x00x00x00x0
0x00x00x17x00x00x00x00x00x00x00xD9x00x00x00x00x00x00x00
xF9x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00xFFxFFxF
FxFFxFFxFFxFFxFFx00x00x00x00x00x00x00x00x00x00x00x00x00
x00x00x00xF9x00x00x00x00x00x00x00x00x00x00x00x00x00x00x0
0x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x03x00
x00x00x00x00x00x00x04x00x00x00x00x00x00x00)x01x00x00x00x
00x00x00x00x00x00x00x03x00x00x00x00x00x00x00xF1x00x00x00
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
== disasm:
#<ISeq:the_sum@(irb)>==================================
0000 trace 8
( 54)
0002 trace 1
( 55)
0004 putobject_OP_INT2FIX_O_1_C_
0005 putobject_OP_INT2FIX_O_1_C_
0006 opt_plus <callinfo!mid:+, argc:1, ARGS_SIM
<callcache>
0009 putobject_OP_INT2FIX_O_1_C_
0010 opt_plus <callinfo!mid:+, argc:1, ARGS_SIM
<callcache>
0013 putobject_OP_INT2FIX_O_1_C_
0014 opt_plus <callinfo!mid:+, argc:1, ARGS_SIM
<callcache>
0017 trace 16
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
opt_plus <callinfo!mid:+,
argc:1…
opt_plus <callinfo!mid:+,
argc:1...
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
putobject_OP_INT2FIX_O_1_C_
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1…
putobject_OP_INT2FIX_O_1_C_
opt_plus <callinfo!mid:+,
argc:1...
n1 > n2 > p1 > n3 > p2 >
n4 > p3
Recursão?
Recursão:
Capacidade que uma rotina
(função ou método) possui
de invocar a si mesma.
Recursão:
Condição de
parada:
Hi
Fulano!
Hi
Fulano!
Hi
Fulano!
Recursão vs
Iteração
Como contar a
quantidade de
itens em uma
lista?
Array
:
Iteração
:
Iteração
:
Array
:
4
Array
:
4
Iteração
:
Iteração
:Array
:
4
Iteração
:
Array
:
4
Transformar todas
as letras em
maiúsculas:
["A", "B", "C",
Mas no dia a dia não
fazemos exatamente
assim...
Como realmente fazemos:
E com recursão?
Head / Tail
“A”
Hea
d
Tail
“B”
Hea
d
“A”
Hea
d
Tail
“A”
Hea
d
Tail
“A”
Hea
d
Tail
Como contar a
quantidade de
itens em uma
lista?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
count(["A", "B", "C",
"D"])
count(["B", "C", "D"])
count(["C", "D"])
count(["D"])
count([])
1 + count(["B", "C",
"D"])
1 + 1 + count(["D",
"D"])
1 + 1 + 1 +
count(["D"])
1 + 1 + 1 + 1 +
count([])
1 + 1 + 1 + 1 + 0
4
Como somar todos
os itens de uma
lista?
1 + sum([2, 2, 2])
1 + 2 + sum([2, 2])
1 + 2 + 2 + sum([2])
1 + 2 + 2 + 2 + sum([])
1 + 2 + 2 + 2 + 0
7
E por aí vai...
Stack Overflow
Stack Overflow
1 + count(["B", "C", "D"])
1 + count(["C", "D"])
1 + count(["D"])
1 + count([])
0
Tamanho do
seu Stack
Stack Overflow
1 + count(["B", "C", "D"])
1 + count(["C", "D"])
1 + count(["D"])
1 + count([])
0
Stack
Overflow
Stack Overflow
1 + count(["B", "C", "D"])
1 + count(["C", "D"])
1 + count(["D"])
1 + count([])
0
stack level too
deep
(SystemStackErro
r)
Stack Overflow
file.rb:7:in `eval':
stack level too deep
(SystemStackError)
from file.rb:7:in `<main>'
Stack Overflow
stack level too
deep
(SystemStackErro
r)
s
1 +
1 +
1 +
1 +
1 +
1 +
1 +
1 +
1 +
1 +
1 +
1 +
1 +
E aí?
Opção 1:
Aumentar o tamanho do
Stack
ulimit -all
core file size (blocks, -c) 0
data seg size (kbytes, -d)
unlimited
scheduling priority (-e) 0
file size (blocks, -f)
unlimited
pending signals (-i)
31321
max locked memory (kbytes, -l)
64
max memory size (kbytes, -m)
unlimited
open files (-n)
1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q)
819200
RubyVM::DEFAULT_PA
RAMS
{
thread_vm_stack_size:
1048576,
thread_machine_stack_size:
1048576,
fiber_vm_stack_size: 131072,
fiber_machine_stack_size:
524288
Opção 2:
Tail Call Optimization
c
Tail Call
Optimization
1 + count(["B", "C", "D"])
1 + count(["C", "D"])
1 + count(["D"])
1 + count([])
0
stack level too
deep
(SystemStackErro
r)
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
c
Tail Call
Optimizationcount(["A", "B", "C", "D"],
0)
count(["B", "C", "D"], 1)
count(["C", "D"], 2)
count(["D"], 3)
count([], 4)
4
Tamanho do
seu Stack
Reaproveitament
o do seu Stack
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
file.rb:11:in `count':
stack level too deep
(SystemStackError)
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:11:in `count'
... 8723 levels...
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:11:in `count'
from file.rb:17:in `<main>'
Precisamos compilar o
nosso código com
instruções específicas
para a RubyVM / YARV
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
== disasm: #<ISeq:count@ppt/tco.rb>=============================
local table (size: 5, argc: 1 [opts: 1, rest: -1, post: 0, block
kwrest: -1])
[ 5] list<Arg> [ 4] acc<Opt=0> [ 3] head [ 2] tail
0000 putobject_OP_INT2FIX_O_0_C_
0001 setlocal_OP__WC__0 4
0003 trace 8
0005 trace 1
0007 getlocal_OP__WC__0 5
0009 opt_empty_p <callinfo!mid:empty?, argc:0, ARGS_SIMPLE>
0012 branchunless 21
0014 nop
0015 nop
0016 getlocal_OP__WC__0 4
0018 trace 16
0020 leave
0021 trace 1
0023 getlocal_OP__WC__0 5
0025 opt_send_without_block <callinfo!mid:shift, argc:0, ARGS_SI
0028 setlocal_OP__WC__0 3
0030 trace 1
0032 getlocal_OP__WC__0 5
0034 setlocal_OP__WC__0 2
== disasm: #<ISeq:count@ppt/tco.rb>=============================
local table (size: 5, argc: 1 [opts: 1, rest: -1, post: 0, block
kwrest: -1])
[ 5] list<Arg> [ 4] accc<Opt=0> [ 3] head [ 2] tail
0000 putobject_OP_INT2FIX_O_0_C_
0001 setlocal_OP__WC__0 4
0003 trace 8
0005 trace 1
0007 getlocal_OP__WC__0 5
0009 opt_empty_p <callinfo!mid:empty?, argc:0, ARGS_SIMPLE>
0012 branchunless 21
0014 nop
0015 nop
0016 getlocal_OP__WC__0 4
0018 trace 16
0020 leave
0021 trace 1
0023 getlocal_OP__WC__0 5
0025 opt_send_without_block <callinfo!mid:shift, argc:0, ARGS_SI
0028 setlocal_OP__WC__0 3
0030 trace 1
0032 getlocal_OP__WC__0 5
0034 setlocal_OP__WC__0 2
Acompanhar eventos
durante a execução do
código internamente na
VM
stackprof
ruby-prof
trace + tail call
optimization
=
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
== disasm: #<ISeq:count@<compiled>>===============================
local table (size: 5, argc: 1 [opts: 1, rest: -1, post: 0, block:
kwrest: -1])
[ 5] list<Arg> [ 4] acc<Opt=0> [ 3] head [ 2] tail
0000 putobject_OP_INT2FIX_O_0_C_
0001 setlocal_OP__WC__0 4
0003 getlocal_OP__WC__0 5
0005 opt_empty_p <callinfo!mid:empty?, argc:0, ARGS_SIMPLE>,
0008 branchunless 15
0010 nop
0011 nop
0012 getlocal_OP__WC__0 4
0014 leave
0015 getlocal_OP__WC__0 5
0017 opt_send_without_block <callinfo!mid:shift, argc:0, ARGS_SIMP
0020 setlocal_OP__WC__0 3
0022 getlocal_OP__WC__0 5
0024 setlocal_OP__WC__0 2
0026 putself
0027 getlocal_OP__WC__0 2
0029 getlocal_OP__WC__0 4
0031 putobject_OP_INT2FIX_O_1_C_
0032 opt_plus <callinfo!mid:+, argc:1, ARGS_SIMPLE>, <call
0035 opt_send_without_block <callinfo!mid:count, argc:2, FCALL|ARG
0008 branchunless 15
0010 nop
0011 nop
0012 getlocal_OP__WC__0 4
0014 leave
0015 getlocal_OP__WC__0 5
0017 opt_send_without_block <callinfo!mid:shift, argc:0, ARGS_SIMP
0020 setlocal_OP__WC__0 3
0022 getlocal_OP__WC__0 5
0024 setlocal_OP__WC__0 2
0026 putself
0027 getlocal_OP__WC__0 2
0029 getlocal_OP__WC__0 4
0031 putobject_OP_INT2FIX_O_1_C_
0032 opt_plus <callinfo!mid:+, argc:1, ARGS_SIMPLE>, <call
0035 opt_send_without_block <callinfo!mid:count, argc:2, FCALL|ARG
<callcache>
0038 leave
0008 branchunless 15
0010 nop
0011 nop
0012 getlocal_OP__WC__0 4
0014 leave
0015 getlocal_OP__WC__0 5
0017 opt_send_without_block <callinfo!mid:shift, argc:0, ARGS_SIMP
0020 setlocal_OP__WC__0 3
0022 getlocal_OP__WC__0 5
0024 setlocal_OP__WC__0 2
0026 putself
0027 getlocal_OP__WC__0 2
0029 getlocal_OP__WC__0 4
0031 putobject_OP_INT2FIX_O_1_C_
0032 opt_plus <callinfo!mid:+, argc:1, ARGS_SIMPLE>, <call
0035 opt_send_without_block <callinfo!mid:count, argc:2, FCALL|ARG
<callcache>
0038 leave
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?
== disasm: #<ISeq:count@<compiled>>===============================
local table (size: 5, argc: 1 [opts: 1, rest: -1, post: 0, block:
kwrest: -1])
[ 5] list<Arg> [ 4] acc<Opt=0> [ 3] head [ 2] tail
0000 putobject_OP_INT2FIX_O_0_C_
0001 setlocal_OP__WC__0 4
0003 getlocal_OP__WC__0 5
0005 opt_empty_p <callinfo!mid:empty?, argc:0, ARGS_SIMPLE>,
0008 branchunless 15
0010 nop
0011 nop
0012 getlocal_OP__WC__0 4
0014 leave
0015 getlocal_OP__WC__0 5
0017 opt_send_without_block <callinfo!mid:shift, argc:0, ARGS_SIMP
0020 setlocal_OP__WC__0 3
0022 getlocal_OP__WC__0 5
0024 setlocal_OP__WC__0 2
0026 putself
0027 getlocal_OP__WC__0 2
0029 getlocal_OP__WC__0 4
0031 putobject_OP_INT2FIX_O_1_C_
0032 opt_plus <callinfo!mid:+, argc:1, ARGS_SIMPLE>, <call
0035 opt_send_without_block <callinfo!mid:count, argc:2, FCALL|TAI
ess 15
OP__WC__0 4
OP__WC__0 5 ( 5)
without_block <callinfo!mid:shift, argc:0, ARGS_SIMPLE>, <callcache
OP__WC__0 3
OP__WC__0 5 ( 6)
OP__WC__0 2
( 8)
OP__WC__0 2
OP__WC__0 4
_OP_INT2FIX_O_1_C_
<callinfo!mid:+, argc:1, ARGS_SIMPLE>, <callcache>
without_block <callinfo!mid:count, argc:2, FCALL|TAILCALL|ARGS_SIMP
100000
0
Por
quê?
Mais rápido que iterar?
user system total
real
.each: 16.480000 0.000000 16.480000
( 16.492415)
recursion: 26.280000 0.380000 26.660000
Maior proximidade
com conceitos de
linguagens
funcionais
Considerada uma
forma elegante de
resolver problemas
Quicksort em C
utilizando
iteração
Quicksort em
Haskell utilizando
recursão
Maneira de lidar
com diferentes
estruturas de
dados
Listas Ligadas
Grafos
Árvores Binárias
Mais uma maneira de
resolver problemas e
entender os detalhes da
linguagem
Referências:
- RubyVM::InstructionSequence
http://ruby-doc.org/core-2.3.1/RubyVM/InstructionSequence.html
- Inline caching in MRI
http://tenderlovemaking.com/2015/12/23/inline-caching-in-mri.html
- Ruby, Trace, Leave, Oh my!
http://kgrz.io/2014/04/19/ruby-trace-leave-oh-my.html
Referências:
- Tail Call Optimization in Ruby
http://nithinbekal.com/posts/ruby-tco/
- Tailin' Ruby
http://timelessrepo.com/tailin-ruby
- Tail Call Optimization in Ruby: Deep Dive
http://blog.tdg5.com/tail-call-optimization-in-ruby-deep-dive/
Referências:
- TCOMethod
Simplifies compiling code with tail call optimization in MRI Ruby
https://github.com/tdg5/tco_method
- Hamster
Efficient, Immutable, Thread-Safe Collection classes for Ruby
https://github.com/hamstergem/hamster
- Functional Ruby
A gem for adding functional programming tools to Ruby. Inspired by
Erlang, Clojure, Haskell, and Functional Java.
https://github.com/jdantonio/functional-ruby
Obrigado!
gbaptista.com.br
Twitter: @guilhermebps
github.com/gbaptista
linkedin.com/in/guilhermebaptista

More Related Content

PPTX
05 - Bypassing DEP, or why ASLR matters
PPTX
07 - Bypassing ASLR, or why X^W matters
PDF
Performance tweaks and tools for Linux (Joe Damato)
PDF
Linux Shellcode disassembling
PDF
Cより速いRubyプログラム
PDF
Debugging Ruby Systems
PDF
Debugging Ruby
PDF
ch8-pv1-the-virtual-filesystem
05 - Bypassing DEP, or why ASLR matters
07 - Bypassing ASLR, or why X^W matters
Performance tweaks and tools for Linux (Joe Damato)
Linux Shellcode disassembling
Cより速いRubyプログラム
Debugging Ruby Systems
Debugging Ruby
ch8-pv1-the-virtual-filesystem

What's hot (20)

PPTX
NTUSTxTDOH 資訊安全基礎工作坊 基礎逆向教育訓練
PDF
Code Vulnerabilities & Attacks
PDF
Php Security
PDF
BlockChain implementation by python
PPS
36 gotas de-sabiduria
PDF
Devel::NYTProf v5 at YAPC::NA 201406
PDF
PL/Perl - New Features in PostgreSQL 9.0
PDF
PGCon 2014 - What Do You Mean my Database Server Core Dumped? - How to Inspec...
PDF
TDOH x 台科 pwn課程
PDF
FreeBSD on Cavium ThunderX System on a Chip
PDF
TDOH 南區 WorkShop 2016 Reversing on Windows
PDF
Introduzione ai network penetration test secondo osstmm
PDF
NTUSTxTDOH - Pwn基礎 2015/12/27
KEY
Hotspot tools
PPTX
Эксплуатируем неэксплуатируемые уязвимости SAP
PDF
An (abridged) Ruby Plumber's Guide to *nix
PDF
Perl at SkyCon'12
PDF
Generator Tricks for Systems Programmers
PDF
Simplest-Ownage-Human-Observed… - Routers
PPTX
EWD 3トレーニングコース#24 GlobalストレージのJavaScript用抽象化-(e) ドキュメントの末端ノードを渡り歩く
NTUSTxTDOH 資訊安全基礎工作坊 基礎逆向教育訓練
Code Vulnerabilities & Attacks
Php Security
BlockChain implementation by python
36 gotas de-sabiduria
Devel::NYTProf v5 at YAPC::NA 201406
PL/Perl - New Features in PostgreSQL 9.0
PGCon 2014 - What Do You Mean my Database Server Core Dumped? - How to Inspec...
TDOH x 台科 pwn課程
FreeBSD on Cavium ThunderX System on a Chip
TDOH 南區 WorkShop 2016 Reversing on Windows
Introduzione ai network penetration test secondo osstmm
NTUSTxTDOH - Pwn基礎 2015/12/27
Hotspot tools
Эксплуатируем неэксплуатируемые уязвимости SAP
An (abridged) Ruby Plumber's Guide to *nix
Perl at SkyCon'12
Generator Tricks for Systems Programmers
Simplest-Ownage-Human-Observed… - Routers
EWD 3トレーニングコース#24 GlobalストレージのJavaScript用抽象化-(e) ドキュメントの末端ノードを渡り歩く
Ad

Viewers also liked (20)

PDF
TDC2016POA | Trilha Web - Garanta a segurança de suas aplicações Web com Keyc...
PDF
TDC2016POA | Trilha Web - A essência do CSS
PDF
Agilizando o desenvolvimento web com SASS
PDF
Levando seu app do iOS para o macOS
PDF
TDC 2016 - Garantindo a qualidade da sua infraestrutura
PDF
TDC 2016 - Sass: CSS com super-poderes.
PPTX
TDC POA 2016 - Robotium + Cucumber + Gradle, misture com spoon e tenha uma ex...
PDF
Como ensinei mais de 1000 testadores
PDF
TDC2016POA | Trilha Web - Realtime applications com Socket.io
PPT
Apresentação tdc 2016 - trilha de testes
PPTX
A transição de um QA tradicional para um Agile Tester
PDF
TDC Floripa 2015 - Branding, UX e Marketing
PDF
Tdc 5 ideias para melhorar os seus testes
PDF
Ensinando e aprendendo com desafios
PDF
TDC2016POA | Trilha Web - JSON API: não reinvente a roda
PPTX
TDC2016POA | Trilha Web - Realidade Virtual com WebVR
PDF
Estou desempregado e agora? Como me recolocar como QA.
PDF
Apresentação de Padrões de Design para Aplicativos Móveis.
PPT
TDC2016POA | Trilha Education - Jogos na Educação, onde estamos errando?
PDF
TDC2016POA | Trilha Empreendedorismo - Manual Prático do Empreendedorismo
TDC2016POA | Trilha Web - Garanta a segurança de suas aplicações Web com Keyc...
TDC2016POA | Trilha Web - A essência do CSS
Agilizando o desenvolvimento web com SASS
Levando seu app do iOS para o macOS
TDC 2016 - Garantindo a qualidade da sua infraestrutura
TDC 2016 - Sass: CSS com super-poderes.
TDC POA 2016 - Robotium + Cucumber + Gradle, misture com spoon e tenha uma ex...
Como ensinei mais de 1000 testadores
TDC2016POA | Trilha Web - Realtime applications com Socket.io
Apresentação tdc 2016 - trilha de testes
A transição de um QA tradicional para um Agile Tester
TDC Floripa 2015 - Branding, UX e Marketing
Tdc 5 ideias para melhorar os seus testes
Ensinando e aprendendo com desafios
TDC2016POA | Trilha Web - JSON API: não reinvente a roda
TDC2016POA | Trilha Web - Realidade Virtual com WebVR
Estou desempregado e agora? Como me recolocar como QA.
Apresentação de Padrões de Design para Aplicativos Móveis.
TDC2016POA | Trilha Education - Jogos na Educação, onde estamos errando?
TDC2016POA | Trilha Empreendedorismo - Manual Prático do Empreendedorismo
Ad

Similar to TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby? (20)

KEY
There and Back Again
PDF
Catch and Throw in Ruby
PPTX
Grow and Shrink - Dynamically Extending the Ruby VM Stack
PDF
Exception Handling: Designing Robust Software in Ruby
PPT
Ruby & Rails Error Handling
PDF
21 ruby exceptions
PPTX
Ruby from zero to hero
PPTX
Day 1 - Intro to Ruby
PDF
Ruby Intro {spection}
ODP
RailswayCon 2010 - Dynamic Language VMs
PDF
Railswaycon Inside Matz Ruby
PDF
Ruby closures, how are they possible?
PDF
New features in Ruby 2.5
PDF
Ruby 2.4 Internals
PDF
Ruby for C#-ers (ScanDevConf 2010)
PDF
Ruby19 osdc-090418222718-phpapp02
PDF
Ruby 1.9
PDF
Impacta - Show Day de Rails
PDF
Exception Handling: Designing Robust Software in Ruby (with presentation note)
PDF
JRuby 9000 - Optimizing Above the JVM
There and Back Again
Catch and Throw in Ruby
Grow and Shrink - Dynamically Extending the Ruby VM Stack
Exception Handling: Designing Robust Software in Ruby
Ruby & Rails Error Handling
21 ruby exceptions
Ruby from zero to hero
Day 1 - Intro to Ruby
Ruby Intro {spection}
RailswayCon 2010 - Dynamic Language VMs
Railswaycon Inside Matz Ruby
Ruby closures, how are they possible?
New features in Ruby 2.5
Ruby 2.4 Internals
Ruby for C#-ers (ScanDevConf 2010)
Ruby19 osdc-090418222718-phpapp02
Ruby 1.9
Impacta - Show Day de Rails
Exception Handling: Designing Robust Software in Ruby (with presentation note)
JRuby 9000 - Optimizing Above the JVM

More from tdc-globalcode (20)

PDF
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
PDF
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
PDF
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
PDF
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
PDF
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
PDF
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
PDF
TDC2019 Intel Software Day - Inferencia de IA em edge devices
PDF
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
PPT
Trilha .Net - Programacao funcional usando f#
PDF
TDC2018SP | Trilha Go - Case Easylocus
PDF
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
PDF
TDC2018SP | Trilha Go - Clean architecture em Golang
PDF
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
PDF
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
PDF
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
PDF
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
PDF
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
PDF
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
PDF
TDC2018SP | Trilha .Net - .NET funcional com F#
PDF
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - Inferencia de IA em edge devices
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha .Net - Programacao funcional usando f#
TDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
master seminar digital applications in india
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Complications of Minimal Access Surgery at WLH
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Computing-Curriculum for Schools in Ghana
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Anesthesia in Laparoscopic Surgery in India
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
master seminar digital applications in india
Microbial disease of the cardiovascular and lymphatic systems
human mycosis Human fungal infections are called human mycosis..pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
O5-L3 Freight Transport Ops (International) V1.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Complications of Minimal Access Surgery at WLH
VCE English Exam - Section C Student Revision Booklet
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Types and Its function , kingdom of life
Computing-Curriculum for Schools in Ghana

TDC2016POA | Trilha Ruby - Stack Level too Deep e Tail Call Optimization: É uma boa ideia fazer recursão em Ruby?