Based on my earlier question, I understand the benefit of using stack allocation. Suppose I have an array of arrays. For example, A
is a list of matrices and each element A[i]
is a 1x3 matrix. The length of A
and the dimension of A[i]
are known at run time (given by the user). Each A[i]
is a matrix of Float64
and this is also known at run time. However, through out the program, I will be modifying the values of A[i]
element by element. What data structure can also allow me to use stack allocation? I tried StaticArrays
but it doesn't allow me to modify a static array.
StaticArrays defines MArray
(MVector
, MMatrix
) types that are fixed-size and mutable. If you use these there's a higher chance of the compiler determining that they can be stack-allocated, but it's not guaranteed. Moreover, since the pattern you're using is that you're passing the mutable state vector into a function which presumably modifies it, it's not going to be valid or helpful to stack allocate that anyway. If you're going to allocate state
once and modify it throughout the program, it doesn't really matter if it is heap or stack allocated—stack allocation is only a big win for objects that are allocated, used locally and then don't escape the local scope, so they can be “freed” simply by popping the stack.
From the code snippet you showed in the linked question, the state
vector is allocated in the outer function, test_for_loop
, which shouldn't be a big deal since it's done once at the beginning of execution. Using a variably sized state vector to index into an array with a splat (...
) might be an issue, however, and that's done in test_function
. Using something with fixed size like MVector
might be better for that. It might, however, be better still, to use a state
tuple and return a new rather than mutated state
tuple at the end. The compiler is very good at turning that kind of thing into very efficient code because of immutability.
Note that by convention test_function
should be called test_function!
since it modifies its M
argument and even more so if it modifies the state
vector.
I would also note that this isn't a great question/answer pair since it's not standalone at all and really just a continuation of your other question. StackOverflow isn't very good for this kind of iterative question/discussion interaction, I'm afraid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With