In the test example below, consumption of resources is very different
depending on whether the ‘working’ function is nested within another
function or is standalone.
Function C: 64.644689 seconds (404.85 M allocations: 11.227 GB, 5.17% gc time)
Function B: 139.715778 seconds (140.43 M allocations: 5.525 GB, 15.78% gc time)
Function C consumes half the time but twice as much memory, if I understand the
output of “@time” correctly, whereas I had not expected major differences.
What are the causes? Is this typical of this scenario?
using Memoize
function C(m, n)
@memoize function c(u, o, t)
if u == -o
return 1
end
if t == 0
return u == 0 ? 0 : sum(c(u-j, o+j-1, (t+1) % m) for j in 1:u)
end
return o == 0 ? 0 : sum(c(u+j-1, o-j, (t+1) % m) for j in 1:o)
end
return c(n, 0, 0)
end
function testC(bound)
for m in 1:20
println([C(m, n) for n in 0:bound])
end
end
@time testC(1)
@time testC(99)
----------
@memoize function b(m, u, o, t)
if u == -o
return 1
end
if t == 0
return u == 0 ? 0 : sum(b(m, u-j, o+j-1, (t+1) % m) for j in 1:u)
end
return o == 0 ? 0 : sum(b(m, u+j-1, o-j, (t+1) % m) for j in 1:o)
end
function B(m, n)
return b(m, n, 0, 0)
end
function testB(bound)
for m in 1:20
println([B(m, n) for n in 0:bound])
end
end
@time testB(1)
@time testB(99)