I have a computation I want to do where I am using my own data structure (composed of two or more arrays, which, themselves, may be specialized data structures). I want to perform an operation on this data structure in a way that will minimize the amount of total computation/allocation by the code. My attempt was to introduce a pre-allocated work space data structure, store the result in the work space, and then swap things so the the work space data structure becomes my main structure. My attempt was as follows:
# toy data structure
struct DataStruct{TF<:AbstractFloat, TI<:Integer}
X::Vector{TF}
Y::Vector{TI}
end
# toy transformation of the sort that would require some
# sort of intermediate data structure.
function struct_func!(S::DataStruct, S_work::DataStruct)
n = length(S.X);
for (j,k) in zip(1:n,n:-1:1)
S_work.X[j] = sin(S.X[j] * (S.Y[k]));
S_work.Y[j] = S.Y[j] - Int(j);
end
# my attempt to change the references to the two structures
S, S_work = S_work, S;
S, S_work
end
S = DataStruct{Float64, Int}(range(0,stop=1, length=5), 2*ones(5));
println(S)
S_work = DataStruct{Float64, Int}(zeros(5), zeros(5));
struct_func!(S,S_work);
println(S);
println(S_work);
This returns:
DataStruct{Float64,Int64}([0.0, 0.25, 0.5, 0.75, 1.0], [2, 2, 2, 2, 2])
DataStruct{Float64,Int64}([0.0, 0.25, 0.5, 0.75, 1.0], [2, 2, 2, 2, 2])
DataStruct{Float64,Int64}([0.0, 0.479426, 0.841471, 0.997495, 0.909297], [1, 0, -1, -2, -3])
indicating that
S, S_work = S_work, S;
does not do what I had hoped it would do.
My thinking had been that this would be like C/C++, where I could just shuffle the pointers, but that’s not working as expected. I would like to doing a second full loop to copy the data over, or allocating another data structure, unless there’s no other straightforward way to do this.