Hello! Physics PhD student here using Julia for a research project.
I have a question regarding what seems to be unnecessary extra memory allocations in my program.
I am using a custom type along the lines of
abstract type SuperType end
mutable struct MyStruct <: SuperType
A::Vector{Float64}
end
As the program runs, I want to update the values the field A for the instances of MyStruct, e.g.
S = MyStruct([0., 0., 0.])
@time S.A = [1,1,1]
Which shows 2 allocations for a total of 160 bytes. While this is not an issue for a few updates, my program involves updating these fields thousands to millions of times per run.
I am surprised that we can update the values in S2, as itās an immutable type. Is this mutability just in reference to the fields the type holds, not the values in said fields? Or does this syntax have to do with BenchmarkTools perhaps?
If the expression you want to benchmark depends on external variables, you should use $ to āinterpolateā them into the benchmark expression to avoid the problems of benchmarking with globals. Essentially, any interpolated variable $x or expression $(...) is āpre-computedā before benchmarking begins:
julia> A = rand(3,3);
julia> @btime inv($A); # we interpolate the global variable A with $A
1.191 Ī¼s (10 allocations: 2.31 KiB)
julia> @btime inv($(rand(3,3))); # interpolation: the rand(3,3) call occurs before benchmarking
1.192 Ī¼s (10 allocations: 2.31 KiB)
julia> @btime inv(rand(3,3)); # the rand(3,3) call is included in the benchmark time
1.295 Ī¼s (11 allocations: 2.47 KiB)