Choose between StaticArrays and regular arrays in a type stable way

For the StaticArrays aficionados here: is it possible to choose dynamically in a type stable way whether an operation is carried out with static arrays or with regular arrays?

No, but as long as you have a function barrier to isolate the type instability, that should be fine.

So in pseudo code

struct MyProblem{T}
    myarray::T
end

function generate_problem(x::Int)
    if x > 100
        problem = MyProblem(DynamicArray)
   else
        problem = MyProblem(StaticArray)
   end
    do_computation(problem)
end

I think one of the important skills to learn with Julia is to be able to exploit that it is dynamic, while still getting the performance benefits of a static language by using function barriers.

6 Likes

But if one of them can be the default output, then 2 variable names can be used and the result can be copied over at the end. I am assuming do_computation is expensive and returns the output as a MyProblem instance when given a static array wrapper but works inplace when passed normal array wrapper. I think this should be type stable if I understand correctly.

function generate_problem(x::Int)
   problem1 = MyProblem(DynamicArray)
   if x > 100
        do_computation(problem1)
   else
        problem2 = MyProblem(StaticArray)
        problem1.myarray .= do_computation(problem2).myarray
   end
   problem1
end