I am new to Julia, but have looked at the manual and searched online, and can’t seem to find the answer to this question. Apologies if I have missed it.
Is there a recommended way to package together functions when calling another function without sacrificing performance?
Attempt at MWE below, with output:
31.843 ms (299492 allocations: 5.33 MiB)
1.875 ms (3 allocations: 781.34 KiB)
suggesting that passing a Function as an argument works well, but passing a Function as a member of a struct does not. If this is unavoidable, then it does quite significantly affect my design decisions. I am particularly interested in the ability to call user-defined functions very many times within a function. Ideally I would like to package functions into a struct (or some other container) so that function interface is kept relatively clean.
struct model
f::Function
end
function alg1(m::model, n::Int64)
array = Vector{Float64}(n)
for i = 1:n
array[i] = m.f(i)
end
return sum(array)
end
function alg2(f::Function, n::Int64)
array = Vector{Float64}(n)
for i = 1:n
array[i] = f(i)
end
return sum(array)
end
function foo(i::Int64)
return sin(i)
end
m = model(foo)
n = 100000
function test1()
alg1(m,n)
end
function test2()
alg2(foo,n)
end
using BenchmarkTools, Compat
@btime test1()
@btime test2()