Hi all,
I’m writing a performance critical function that will be called many times within an optimization loop.
I have several questions regarding how to make it as efficient as possible, but I’ll break those down so that each has it’s own reply and may be more useful for everyone learning how to code efficiently in Julia (like me).
I read that in-place assignment of vectors is very important to avoid spending time allocating the same variable every time a function is called, and I verified it with simple functions.
This is something that in C or Fortran I would do through static variables, but apparently they are not a thing in Julia (yet?), so we have to pass the variable to be modified as an input to the function as well, and do in-place assignment with lines like
b[:] = a
Now, what if I have to update a scalar as part of the same function?
I tried benchmarking the following function
function f1!(a,b)
b = a
return nothing
end
And I got
BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 0.001 ns (0.00% GC)
median time: 0.001 ns (0.00% GC)
mean time: 0.027 ns (0.00% GC)
maximum time: 0.100 ns (0.00% GC)
--------------
samples: 10000
evals/sample: 1000
So the function does not allocate as expected, but b is modified only inside the function: outside, where b was created and initialized, b still has the same value as before.
If I create the vector version of this function, I have to explicitly write the in place assignment
function f2!(a,b)
b[:] = a
return nothing
end
which works as expected and does not allocate anything.
I cannot use f2! for scalars, because the indexing operation is not defined on those, so I have a properly(?) working function that works on vectors but not for scalars.
Can someone help me understand what’s wrong in anything I wrote?
Thanks